[TDD] Jest

M_yeon·2023년 5월 3일
0

TDD

목록 보기
2/2

간단한 버튼 테스트부터 진행해보려 한다.

  1. 컴포넌트가 정상적으로 생성된다.
  2. button 이라고 쓰여있는 엘리먼트는 HTMLButtonElement이다.
  3. 버튼을 클릭하면, p 태그 안에 "버튼이 방금 눌렸다"라고 쓰여진다.
  4. 버튼을 클릭하기 전에는 p태그 안에 "버튼이 눌리지 않았다"라고 쓰여진다.
  5. 버튼을 클릭하고 5초 뒤에는 p태그 안에 "버튼이 눌리지 않았다"라고 쓰여진다.
  6. 버튼을 클릭하면 5초 동안 버튼이 비활성화 된다.

1. 컴포넌트가 정상적으로 생성된다.

// button.jsx를 의미
describe('Button 컴포넌트 @testing-library/react', () => {
  it('컴포넌트가 정상적으로 생성된다.', () => {
    const button = render(<Button/>);
	expect(button).not.toBe(null);
  })
})

2. button 이라고 쓰여있는 엘리먼트는 HTMLButtonElement이다.

  it('button 이라고 쓰여있는 엘리먼트는 HTMLButtonElement이다.', () => {
    const {getByText} = render(<Button/>);
                               
	const buttonElement = getByText('text');
    expect(buttonElement).toBeInstanceOf(HTMLButtonElement);
    // text를 가지고 있는 요소가 button이 맞느냐
  })

3. 버튼을 클릭하면, p 태그 안에 "버튼이 방금 눌렸다"라고 쓰여진다.

  it('버튼을 클릭하면, p 태그 안에 "버튼이 방금 눌렸다"라고 쓰여진다.', () => {
    const {getByText} = render(<Button/>);
	const buttonElement = getByText('text');
    
    fireEvent.click(buttonElement);
    const p = getByText('버튼이 방금 눌렸다.');
    
    expect(p).not.toBeNull();
    expect(p).toBeInstanceOf(HTMLPragraphElement);
  })

4. 버튼을 클릭하기 전에는 p태그 안에 "버튼이 눌리지 않았다"라고 쓰여진다.

  it('버튼을 클릭하기 전에는 p태그 안에 "버튼이 눌리지 않았다"라고 쓰여진다.', () => {
    const {getByText} = render(<Button/>);
    
    const p = getByText('버튼이 눌리지 않았다');
    
    expect(p).not.toBeNull();
    expect(p).toBeInstanceOf(HTMLPragraphElement);
  })

5. 버튼을 클릭하고 5초 뒤에는 p태그 안에 "버튼이 눌리지 않았다"라고 쓰여진다.

  it('버튼을 클릭하고 5초 뒤에는 p태그 안에 "버튼이 눌리지 않았다"라고 쓰여진다.', () => {
    jest.useFakeTimers();
    
    const {getByText} = render(<Button/>);
	const buttonElement = getByText('text');
    
    fireEvent.click(buttonElement);
    // 클릭후 5초가 흘러야 함
    
    act(() => {
	    jest.advenceTimersByTime(5000);
    })
    
    const p = getByText('버튼이 눌리지 않았다');
    expect(p).not.toBeNull();
    expect(p).toBeInstanceOf(HTMLPragraphElement);
  })

6. 버튼을 클릭하면 5초 동안 버튼이 비활성화 된다.

  it('버튼을 클릭하면 5초 동안 버튼이 비활성화 된다.', () => {
    jest.useFakeTimers();
    
    const {getByText} = render(<Button/>);
	const buttonElement = getByText('text');
    
    fireEvent.click(buttonElement);
    
    expect(buttonElement.disabled).toBeDisabled();
    
    act(() => {
	    jest.advenceTimersByTime(5000);
    })
    
    expect(buttonElement.disabled).not.toBeDisabled();
  })

번외

5초가 흐르는 부분에서 jest는 시간에 제약받지 않기 위해 페이크 타이머를 지원한다.

jest.useFakeTimers();
jest.advenceTimersByTime(5000); // ms

fireEvent를 사용하게 되면 아래같은 에러가 뜨는데

act(() => {
	/* fire events that update state*/
})

변화가 있는 state로 테스트를 할 때 act라는 함수를 사용해서 안에 함수를 작성하라는건데 모든 함수는 이 act를 사용하는게 좋다고 한다.
https://legacy.reactjs.org/docs/testing-recipes.html

Arrange Act Assert 패턴

0개의 댓글