Jest
- 설치
sudo npm i --save-dev @nestjs/testing
describe(name, fn)
- 여러 관련 테스트를 그룹화하는 블록 생성
- Promise
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
jest
- Mokcing
- jest.fn()
- mock function을 생성할 수 있음
const mockFn = jest.fn();
mockImplementation
- mock function을 즉석에서 구현
mockFn.mockImplementation((name) => `I am ${name}!`);
console.log(mockFn("Dale")); // I am Dale!
- 해당 함수의 호출 여부와 어떻게 호출되었는지만을 알아야 할 때
const calculator = {
add: (a, b) => a + b,
};
const spyFn = jest.spyOn(calculator, "add");
const result = calculator.add(2, 3);
expect(spyFn).toHaveBeenCalledTimes(1);
expect(spyFn).toHaveBeenCalledWith(2, 3);
expect(result).toBe(5);
- Matcher
- toEqual()
- toBeTruthy(), toBeFalsy()
- true, false 확인
- toHaveLength(), toContain()
- 배열 길이, 특정 원소 존재 여부 확인
- toBe(), toMatch()
- toBe()는 문자열이 정확히 일치하는지 체크하지만
- toMatch()는 정규식 기반의 테스트를 진행한다.
test("string", () => {
expect(getUser(1).email).toBe("user1@test.com");
expect(getUser(2).email).toMatch(/.*test.com$/);
});
- 예외 발생 여부를 테스트한다
- string을 인자로 받을 경우 예외 메세지를 비교한다.
jest.config - mouduleNameMapper @ 경로 인식 에러 해결하기
ref - [체인의정석:티스토리]
https://it-timehacker.tistory.com/95
- Jest 테스트 모듈 생성 중
Path Alias
를 못 불러오는 에러 발생
import { ProducerService } from '@kafka/producer.service'; // -> alias
describe('AppController', () => {
let appController: AppController;
let appService: AppService;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService, ProducerService]
}).compile();
appController = app.get<AppController>(AppController);
appService = app.get<AppService>(AppService);
});
}
mouduleNameMapper
로 따로 path 매핑 설정을 해주어야 한다고 한다.- tsconfig.json에 설정해둔 path
{
"compilerOptions": {
...
"paths": {
"@kafka": [
"src/kafka"
],
"@kafka/*": [
"src/kafka/*"
],
...
}
}
}
- test/jest.config.json
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "..",
"testEnvironment": "node",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"moduleNameMapper": {
"@auth/(.*)$": "<rootDir>/src/auth/auth/$1",
"@role/(.*)$": "<rootDir>/src/auth/role/$1",
"@common/(.*)$": "<rootDir>/src/common/$1",
"@config/(.*)$": "<rootDir>/src/config/$1",
"@db/(.*)$": "<rootDir>/src/db/$1",
"@kafka/(.*)$": "<rootDir>/src/kafka/$1",
"@user/(.*)$": "<rootDir>/src/user/$1"
}
}
- package.json script에 jest config 적용
// before
"test": "jest",
//after
"test": "jest --config ./test/jest.config.json",
Share article