[React Projects]06.HotelReview

Crazy.K·2022년 7월 20일
0

React Projects 2019

목록 보기
6/6

Github

===== 2022-11-30 수정 =====
아무리 나라도 내용 정리가 너무 부실한것 같아 보완함

JEST를 이용한 테스트
테스트 파일은 컴포넌트와 동일한 파일명에 test.js로 끝나면 된다
예를 들어 Button.test.js
생각해보면 꼭 컴포넌트와 같아야 하는가?
아닌것 같은데 해보기 귀찮다

import React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
import Button from "./Button";

// 테스트 내용 설명
describe('the <Button/> component', () => {
	// 렌더러 생성
	const renderer = new ShallowRenderer();

	// it 함수 하나하나가 테스트 함수. 가독성을 위한 메소드 명명 방식
	it('should render', () => {
		const children = 'This is a button';
		renderer.render(<Button>{children}</Button>);
		const result = renderer.getRenderOutput();
        // 스냅샷이 없으면 생성된다
		expect(result).toMatchSnapshot();
	});

	it('should render the correct children', () => {
		const children = 'This is a button 2';
		renderer.render(<Button>{ children }</Button>);
		const result = renderer.getRenderOutput();
        // assert라고 생각하면 된다
		expect(result.props.children).toEqual(children);
	});
});

react-test-renderer의 ShallowRenderer를 사용하여
렌더링 하고 내용을 확인 할 수 있다

enzyme을 가지고 테스트 하면 아래와 같다

import React from 'react';
import Button from "./Button";
import {shallow} from "enzyme";

describe('the <Button/> component with shallow of the enzyme', () => {
	it('should render', () => {
		const children = 'This is a button with enzyme';
		const component = shallow(<Button>{ children }</Button>);
		expect(component).toMatchSnapshot();
	});

	it('should render the correct children', () => {
		const children = 'This is a button with enzyme';
		const component = shallow(<Button>{ children }</Button>);
		expect(component.props().children).toEqual(children);
	});

	it('should handle the onClick event', () => {
    	// 테스트용 이벤트 핸들러 
		const mockOnClick = jest.fn();
		const component = shallow(<Button onClick={mockOnClick}/>);
        // 클릭처리
		component.simulate('click');
        // 호출이 되었는가
		expect(mockOnClick).toHaveBeenCalled();
	});
});

===== original =====

05번 프로젝트와 90% 동일하며
JEST 사용에 대한 내용으로만 구성되어 있음

ShallowRenderer 를 사용하는건 좀 맞지 않아보였다

enzyme을 사용하면 shallow 함수로 스냅샷을 만들 수 있다

import { shallow } from 'enzyme'
const component = shallow(<SomeCompo/>);

UI 요소는 태그와 at 메소드로 가져올 수 있다
가상의 함수를 만들고 호출 여부를 판단할 수 있다

const mockOnButtonClick = jest.fn()
const component = shallow(<SomeCompo onButtonClick={ mockOnButtonClick }/>);
const button = component.find(Button).at(0)
button.simulate('click');

expect(mockOnButtonClick).toHaveBeenCalled();

현재 보고 있는 내용이 버전이 낮고
바람직한 내용보다는 저자의 개인적인 취향
혹은 그 외의 무언가를 바탕으로 작성되어 있는것을
충분히 감안해야 한다

profile
미치도록 하기 싫다...

0개의 댓글