티스토리 뷰
- Jest에서 아래와 같이 테스트를 하면, 테스트항목을 나타내준다.
위의 사진은 샘플 프로젝트에서 npm run test 수행 결과이다.
테스트케이스가 너무 많아서 시간이 오래걸리면 안뜬다.
그냥 .spec.ts 테스트 파일 한개만 테스트하면 위의사진과 같이 표기가된다.
users.controller.spec.ts 파일만 테스트
$ npm run test users.controller
그런데 본격적으로 사용해야되는 프로젝트에서는 테스트항목이 나타나있지 않다... 왜일까?
그리고 Warning 문구가 있다. 저 문구가 너무 거슬린다!
A worker process has failed to exit gracefully and has been force exited.
This is likely caused by tests leaking due to improper teardown.
Try running with --detectOpenHandles to find leaks.
Active timers can also cause this, ensure that .unref() was called on them.
[해결방안1] jest --runInBand --detectOpenHandles
아래 사이트를 참고해보니 package.json 에서 추가하면된다.
고친후 다시 테스트 해보니 통과 였던 케이스도 실패케이스로 떴다.
{
"scripts":{
...
"test": "jest --runInBand --detectOpenHandles",
...
}
}
[해결방안 2]
(1) package.json 의 jest에서 --forceExit 태그 추가
// package.json
"jest": "jest --runInBand --detectOpenHandles --forceExit"
(2) body-parser 설치
Jest has detected the following 1 open handle potentially keeping Jest from exiting:
$ npm install -D body-parser
body-parser 설치후에는 .expect() 에서 에러 표시가 난다.
이번엔 어디가 잘못된걸까...
Guard Overiding 하기
Guard에 진입할 때 MockFunction 만들기
const mockGuards = {
CanActivate: jest.fn(() => true)
}
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
controllers: [UsersController, AuthController],
providers: [
...,
LocalAuthGuard,
UserNotSellerGuard,
AuthService,
],
})
.overrideGuard(LocalAuthGuard) // LocalAuthGuard 오버라이드
.useValue(mockGuards)
.overrideGuard(UserNotSellerGuard) // UserNotSellerGuard 오버라이드
.useValue(mockGuards)
.compile();
app = moduleFixture.createNestApplication();
app.setGlobalPrefix('/api');
app.useGlobalPipes(
new ValidationPipe({ transform: true, whitelist: true }),
);
await app.init();
...
});
it('should be defined', () => {
expect(userController).toBeDefined();
});
https://stackoverflow.com/questions/55848238/nestjs-unit-test-mock-method-guard
process.env 를 읽을 수 없을 때 해결방법
const { SESSION_ID, COOKIE_SECRET } = process.env;
https://github.com/vuejs/vue-test-utils/issues/193
mongoose 의 save(), exec() 함수를 인식할 수 없다고하는 에러를 발견시
필자의 경우에 save() 와 exec() 을 제거하니까 정상동작이 됐다.
https://stackoverflow.com/questions/51331620/jest-mockgoose-doc-save-doesnt-work-async-await
이번에는 테스트를 전부통과했는데도 빨간글씨가 에러문같아보여서 한번 검색해봤다.
package.json에서 "jest --runInBand --detectOpenHandles --forceExit" 로 테스트를 런타임에 돌리게되는데
"detectOpenHandles" 옵션때문에 발생하는거라고 한다.
즉 handler함수( ^ 표시된 부분) 이 종료되면 에러 발생이 날 수 있다는 표시이다.
즉 에러문은 아니므로 안심해도된다 ㅎㅎㅎ
한마디로 요약하자면 detectOpenHandles옵션은 '테스트 케이스를 더 디테일하게 보고' 하는 역할이다.
어떤 핸들러에서 잠정적으로 에러가 발생하는지를 추정하는 역할을 한다.
[ mocking 사용하는 방법 ]
'Backend > 꾸준히 TIL' 카테고리의 다른 글
[NestJS+Mongoose] NestJS 에서 mongoose.populate() 사용하기 (0) | 2022.11.16 |
---|---|
[NestJS+Mongoose] Cast to date failed for value "[Function: now]" 에러 해결 (0) | 2022.11.16 |
[Node.js] nvm 버젼 변경 (0) | 2022.11.13 |
[NestJS] Joi: Cannot read properties of object undefined (0) | 2022.11.12 |
[NestJS + MongoDB ] NestJS 프레임워크에 MongoDB 연결해보자 (0) | 2022.11.12 |
- Total
- Today
- Yesterday
- 스마트폰중독
- git
- 클린아키텍쳐
- 한달독서
- nestjs
- typeORM
- vscode
- 한달어스
- 바이트디그리
- nestjs jest
- 디지털디톡스
- 개발용어
- Nest.js
- Mongoose
- gem
- MySQL
- TDD
- 습관개선
- 미완
- jest
- TypeScript
- IT용어
- 나도 할 수 있다
- node.js
- 참고
- Jekyll
- OS
- 갓생살자
- MongoDB
- RDBMS
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |