Jest 주로 사용하는 메서드 모음

오늘처음해요·2025년 7월 13일
0

객체 테스트

  • toStrictEqual
  • toMatchObject

함수 테스트

  • toHaveBeenCalledTimes
  • toHaveBeenCalledWith
  • 메서드를 테스트할 때는 jest.fn()
  • 객체 안의 메서드를 테스트할 때는 jest.spyOn(obj, "메서드 이름")

모킹

  • mockImplementation( ( ) ⇒ { } )
    • 내가 원하는 동작으로 변경할 수 있음
  • mockImplementationOnce( ( ) ⇒ { } )
    • 한번만 내가 원하는 대로 실행되게 할 수 있음
  • mockReturnValue()
    • 반환 값만 바꾸고 싶을 때
  • mockReturnValueOnce()
    • 반환 값을 내가 원하는 걸로 한번만 반환되게 하는 법

비동기 함수 테스트

  • mockResolvedValue
  • mockRejectedValue
  • 웬만하면 expect.assertions(1)로 실제 expect가 실행되는지 확인해주는 것이 좋음
  • 주의해야 하는 사항
    • 비동기 테스트할 때 반드시 return 을 넣어줘야 함
    • return이 없으면 테스트가 종료되기 전에 끝나서 정확한 테스트가 불가
    • 대신 테스트 내부 메서드에 async를 붙이게 되면 return 없어도 됨
  • 비동기 테스트 하는 방법
    • Promise, Async 둘 다 방법은 똑같음

    • resolves / rejects 사용

      test('Promise 성공 테스트1', () => {
        expect(successPromise).resolves.toBe('성공');
      });
      
      test('Promise 실패 테스트1', () => {
        expect(failPromise()).rejects.toThrow('실패');
      });
    • then / catch사용

      test('Promise 성공 테스트2', () => {
        const spyOn = jest.fn(successPromise);
        return spyOn().then(() => {
          expect(spyOn).toHaveBeenCalledWith('성공');
        });
      });
      
      test('Promise 실패 테스트2', () => {
        return failPromise().catch((e) => {
          expect(e).toEqual(new Error('실패'));
        });
      });
    • async / await 사용

      test('Promise 성공 테스트3', async () => {
        const result = await successPromise();
        expect(result).toBe('성공');
      });
      
      test('Promise 실패 테스트3', async () => {
        try {
          await failPromise();
        } catch (e: any) {
          expect(e).toBeInstanceOf(Error);
          expect(e.message).toBe('실패');
        }
      });

에러 테스트

  • toThrow
  • 에러 테스트를 바로 호출하면 에러가 나고 끝나서 콜백으로 감싸줘야 함
    test('에러 테스트', () => {
    	expect( () => error()).toThrow(Error);
    })

스파이 없애는 법

  • mockClear
    • 함수가 누구랑 실행되었는지, 몇 번 호출 되었는 지만 초기화
    • toHaveBeenCalledTimes + With 초기화
  • mockReset
    • mockClear + mockImplementation 초기화
  • mockRestore
    • 아예 없애버림
  • clearAllMocks
  • resetAllMocks

테스트 라이프 사이클

  • beforeEach, afterEach
    • 각 테스트 단위
  • beforeAll, afterAll
    • 파일 단위

시간 / 날짜 테스트

  • useFakeTimers
  • useRealTimers
  • jest는 타이머 관련 기능 테스트가 잘되어있어서 공식 문서 보면 좋음

모킹

  • jest.mock
    • 모듈 자체를 모킹하는 기능
    • 호이스트링 되어서 맨 위에서 호출된 거랑 똑같은 동작을 함
    • 차라리 mock을 쓸거면 맨 위에서 선언하는 게 좋음

0개의 댓글