티스토리 뷰

728x90
반응형

- 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",
  ...
 }
}
 

jest run reports "A worker process has failed to exit gracefully ..." · Issue #524 · testing-library/dom-testing-library

DOM Testing Library version: 7.2.1 node version: 10.15.3 npm (or yarn) version: 6.13.6 Relevant code or config: require('@testing-library/dom'); What you did: See above. What happened: Jest...

github.com

 

 


[해결방안 2]

(1) package.json 의 jest에서  --forceExit 태그 추가

// package.json

"jest": "jest --runInBand --detectOpenHandles --forceExit"
 

Jest has detected the following 1 open handle potentially keeping Jest from exiting: TCPSERVERWRAP

I am doing a basic end to end testing here, for the moment it's failing, but first I can't get rid of the open handle. Ran all test suites. Jest has detected the following 1 open handle potentially

stackoverflow.com

 

(2) body-parser 설치

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

 

 

$ npm install -D body-parser
 

open handles with body-parser#1.20.0 · Issue #772 · visionmedia/supertest

Hallo, jest test run does not exit and instead prints this error Jest has detected the following 64 open handles potentially keeping Jest from exiting: ● bound-anonymous-fn 23 | 24 | const response...

github.com

 

 

 

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

 

Nestjs unit-test - mock method guard

I have started to work with NestJS and have a question about mocking guards for unit-test. I'm trying to test a basic HTTP controller that has a method Guard attach to it. My issue started when I

stackoverflow.com


process.env 를 읽을 수 없을 때 해결방법

const { SESSION_ID, COOKIE_SECRET } = process.env;

https://github.com/vuejs/vue-test-utils/issues/193

 

How can I use Environment Veriables with Jest · Issue #193 · vuejs/vue-test-utils

I would like to raise this issue again, as I have not been able to find an acceptable solution. If you feel it is not related to this project please close it and I will stop the pestering 😉 I am us...

github.com


mongoose 의 save(), exec() 함수를 인식할 수 없다고하는 에러를 발견시

필자의 경우에 save() 와 exec() 을 제거하니까 정상동작이 됐다.

https://stackoverflow.com/questions/51331620/jest-mockgoose-doc-save-doesnt-work-async-await

 

Jest Mockgoose Doc.save() doesn't work async/await

I'm using jest on my e-commerce software so I can also do render tests when end-to-end testing (themes are supported, that's why). But I'm currently just testing some mongoose functionality and whe...

stackoverflow.com


이번에는 테스트를 전부통과했는데도 빨간글씨가 에러문같아보여서 한번 검색해봤다.

package.json에서  "jest --runInBand --detectOpenHandles --forceExit" 로 테스트를 런타임에 돌리게되는데

"detectOpenHandles" 옵션때문에 발생하는거라고 한다.

즉 handler함수( ^ 표시된 부분) 이 종료되면 에러 발생이 날 수 있다는 표시이다.

즉 에러문은 아니므로 안심해도된다 ㅎㅎㅎ

 

한마디로 요약하자면 detectOpenHandles옵션은 '테스트 케이스를 더 디테일하게 보고' 하는 역할이다.

어떤 핸들러에서 잠정적으로 에러가 발생하는지를 추정하는 역할을 한다.

 

How to fix err Jest has detected the following 3 open handles potentially keeping Jest from exiting

Just starting to work on some node app using jest for testing. express-generator used for scaffolding. On first test I get following error: Jest has detected the following 3 open handles potent...

stackoverflow.com

 

 

[ mocking 사용하는 방법 ]

 

[Jest] Mocking 사용하기

mocking이란 (mock = 모조품) 뜻 그대로 받아드리면 된다.즉 테스트하고자 하는 코드가 의존하는 function이나 class에 대해 모조품을 만들어 '일단' 돌아가게 하는 것이다.한마디로, 단위 테스트를 작성

velog.io

 

728x90
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함