react-testing-library, Jest

HyosikPark·2020년 12월 10일
0

react

목록 보기
3/6
npm i jest

vs Code에서 인텔리센스 지원 받는 법
npm i @types/jest

// package.json
"scripts": {
    "test": "jest --watchAll --verbose"
  }

//sum.test.js
const { sum, sumOf } = require('./sum');

describe('sum', () => {
  it('calculates 1 + 2', () => {
    expect(sum(1, 2)).toBe(3);
  });

  it('calculates all numbers', () => {
    const array = [1, 2, 3, 4, 5];
    expect(sumOf(array)).toBe(15);
  });
});

TDD
실패, 성공, 리팩토링으로 구성

1. 실패하는 테스트 케이스 먼저 만들기
2. 테스트 통과
3. 리팩토링

toBe, toEqual 차이
toBe: 값을 비교할 때 사용 toBe(1);
toEqual: 객체나 배열을 비교할 때 사용 toEqual([1,2]);

스냅샷 테스팅
렌더링 결과가 이전의 렌더링 결과와 일치하는지 확인하는 작업
npm i enzyme-to-json

이미 설치된 리액트에 타입스크립트 생성

react-testing-library
render(component) : render함수에 컴포넌트를 입력하면 다양한 DOM query 및 container가 반환
container: 해당 컴포넌트의 최상위 DOM

스냅샷 테스팅: 렌더링 결과가 이전에 렌더링한 결과와 일치하는지 확인하는 작업.
렌더링 결과가 이전과 일치하지 않을 경우 fail : ex) 컴포넌트에 내용이 추가 됐다거나 등등
스냅샷 업데이트 : 테스트 fail시 테스트 터미널 창에서 u키 입력

render 쿼리 함수 종류
variant와 queries를 조합하여 사용 ex) getByText

Variant
getBy* : 쿼리 조건에 일치하는 dom엘리먼트 하나 선택
getAllBy* : 쿼리조건에 일치하는 DOM 엘리먼트 여러개 선택
queryBy* : 조건에 일치하는 DOM 엘리먼트 선택, 존재하지 않아도 에러 발생 x
queryAllBy* : 조건에 일치하는 DOM 엘리먼트 여러개 선택, 존재하지 않아도 에러 발생 x
findBy*: 조건에 일치하는 DOM 엘리먼트 Promise 반환, 4500ms전에 나타나지 않으면 에러 발생 
findAllBy: 여러개

Queries
ByLabelText(text): input이 label을 가지고 있으면, label의 텍스트로 input elem 선택.
ByPlaceholderText(value): placeholder 값으로 input 및 textarea elem 선택.
ByText(): 엘리먼트가 가지고 있는 텍스트 값으로 elem 선택
ByAltText(): alt속성을 가지고 있는 elem 선택
ByTitle(): title 속성 값을 가지는 elem, SVG elem 선택
ByDisplayValue: value 속성 값으로 input, textarea, select elem 선택
ByRole: role속성 값으로 elm선택
ByTestId: elem을 선택할 마땅할 방법이 없을 때 elem에 <div data-testid="value"> 속성을 넣어 그 값으로 elem선택

쿼리사용 권장 순서
getByLabelText
getByPlaceholderText
getByText
getByDisplayValue
getByAltText
getByTitle
getByRole
getByTestId

fireEvent 사용법

import {fireEvfent} from '@testing-library/react';
 
fireEvent.이벤트이름(DOM, 이벤트 객체)-

ex) fireEvent.change(myInput, {target: value: 'ok'});

toHaveAttribute('attribute', 'value') : 해당 elem의 속성 value 값이 일치하는지 확인.
toHaveStyle('text-decoration: line-through;') 스타일 속성 일치 확인


jest.fn() : matcher를 사용해서 함수가 호출 됐는지, 됐다면 파라미터가 무엇인지 등을 알 수 있다.
ex) const onInsert = jest.fn();
render(<TodoForm onInsert={onInsert});
expect(onInsert).toBeCalledWith('TDD') 
toBeCalledWith: 전달된 함수 파라미터 값.

expect().not.method() : 메서드에 대응되지 않는지 확인.
expect().toBeNull() : null인지 확인;

0개의 댓글