출처: https://docs.firstdecode.com/tdd/
TDD란, 작은 단위로 테스트 케이스를 작성하고 이를 통과하는 코드를 작성하는 과정을 반복하는 것을 의미한다.
시간이 오래 걸릴수도 있지만, 예상치 못했던 버그를 줄여서 장기적으로는 같은 일을 여러번 더 하게 되지 않을 수 있다.
Testing 용도로 많이 쓰이는 것들중 하나인 Jest가 있다.
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
위 코드처럼 test
함수를 이용할 때 첫번째 인자로는 테스트에 대한 설명이고 두 번째 인자로 테스트하고자 하는 것을 함수형태로 넣어야 한다.
통과되지 않았을 때 throw
키워드를 이용하여 에러메시지 전달을 하거나
비동기 처리로 할 수도 있다.
// Testing for async errors using Promise.catch.
it('tests error with promises', () => {
expect.assertions(1);
return user.getUserName(2).catch(e =>
expect(e).toEqual({
error: 'User with 2 not found.',
}),
);
});
// Or using async/await.
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await user.getUserName(1);
} catch (e) {
expect(e).toEqual({
error: 'User with 1 not found.',
});
}
});
보통 npx create-react-app
으로 리액트 앱을 설치하면 package.json
의dependencies 안에 testing 관련 패키지가 추가되는데 한번 이게 무엇인지 알아봤다.
@testing-library/jest-dom
: jest-dom에서 제공하는 Custom Mathcer를 사용할 수 있게 한다.
@testing-library/react
: jest와 같이 많이 쓰이는 React-testing-library
의 일종이라고 보면 될 것 같다.
@testing-library/user-event
: click 등 사용자 이벤트에 이용된다.
import {render, screen} from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import '@testing-library/jest-dom'
import Fetch from './fetch'
test('loads and displays greeting', async () => {
// ARRANGE
render(<Fetch url="/greeting" />) // 테스트를 진행할 컴포넌트를 render 함수로 전달한다.
// ACT
// screen의 메소드 중 getByText를 이용해서 해당 컴포넌트 안에 `Load Greeting`이라는 문자열이 있는지 확인
await userEvent.click(screen.getByText('Load Greeting'))
await screen.findByRole('heading')
// ASSERT
//expect와 toHaveTextContent로 텍스트가 예상과 일치하는지 확인
expect(screen.getByRole('heading')).toHaveTextContent('hello there')
})
참고자료 : Jest 공식문서, React Testing Library