본문 바로가기
카테고리 없음

[JavaScript] Jest로 테스트 코드 작성하기

by hbIncoding 2024. 7. 23.

1. Jest 환경 설정

  • Jest 설치하기
    • npm i --save-dev jest
    • 실행은 npm test 로 실행
    • packge.json 파일 수정
  "scripts": {
    "test": "jest"
  },

 

  • test 파일 작성하기
    • main.test.js 와 같이 .test.을 넣어주면 test시에 테스트 파일만 읽어서 테스트를 수행한다.
  • 여러가지 matcher
    • 부정문을 쓸경우 not을 붙여주면 된다.
      • ex) expect('A').not.toBe('B')
    • toBe: Object.is를 사용하여 값이 일치하는지 확인합니다. 원시 타입 값 비교에 사용됩니다.
    • toEqual: 객체나 배열의 내용을 비교합니다.
    • toBeNull: 값이 null인지 확인합니다.
    • toBeUndefined: 값이 undefined인지 확인합니다.
    • toBeDefined: 값이 정의되어 있는지 확인합니다.
    • toBeTruthy: 값이 참(true)인지 확인합니다.
    • toBeFalsy: 값이 거짓(false)인지 확인합니다.
    • toBeGreaterThan: 값이 특정 값보다 큰지 확인합니다.
    • toBeGreaterThanOrEqual: 값이 특정 값보다 크거나 같은지 확인합니다.
    • toBeLessThan: 값이 특정 값보다 작은지 확인합니다.
    • toBeLessThanOrEqual: 값이 특정 값보다 작거나 같은지 확인합니다.
    • toBeCloseTo: 부동 소수점 숫자의 근사값을 확인합니다.
    • toMatch: 문자열이 정규 표현식에 일치하는지 확인합니다.
    • toContain: 배열이나 iterable 객체에 특정 항목이 포함되어 있는지 확인합니다.
    • toHaveLength: 객체의 길이를 확인합니다.
    • toHaveProperty: 객체에 특정 속성이 있는지 확인합니다.
expect(2 + 2).toBe(4);
expect({ name: 'John' }).toEqual({ name: 'John' });
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect(1).toBeDefined();
expect(true).toBeTruthy();
expect(false).toBeFalsy();
expect(10).toBeGreaterThan(5);
expect(10).toBeGreaterThanOrEqual(10);
expect(5).toBeLessThan(10);
expect(10).toBeLessThanOrEqual(10);
expect(0.1 + 0.2).toBeCloseTo(0.3);
expect('Hello, World!').toMatch(/World/);
expect(['Alice', 'Bob', 'Eve']).toContain('Bob');
expect([1, 2, 3]).toHaveLength(3);
expect({ name: 'John' }).toHaveProperty('name');

 

  • 예외 처리 매처
    • toThrow: 함수가 호출될 때 예외를 던지는지 확인합니다.
    • toThrowError: 함수가 특정 에러를 던지는지 확인합니다.
expect(() => { throw new Error('error') }).toThrow();
expect(() => { throw new Error('error') }).toThrowError('error');
  • 비동기 코드 매처
    • resolves: 프로미스가 성공했을 때의 값을 확인합니다.
    • rejects: 프로미스가 실패했을 때의 에러를 확인합니다.
await expect(Promise.resolve('value')).resolves.toBe('value');
await expect(Promise.reject(new Error('error'))).rejects.toThrow('error');