programing

Jest가 다음 1개의 열린 핸들을 탐지하여 Jest가 종료되지 않도록 할 수 있습니다. TCPSERVERWRAP

jooyons 2023. 6. 9. 22:01
반응형

Jest가 다음 1개의 열린 핸들을 탐지하여 Jest가 종료되지 않도록 할 수 있습니다. TCPSERVERWRAP

저는 여기서 기본적인 엔드 투 엔드 테스트를 하고 있습니다. 현재는 실패하고 있지만, 먼저 열려 있는 손잡이를 제거할 수 없습니다.

Ran all test suites.

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

  ●  TCPSERVERWRAP

      40 |     }
      41 |     return request(app.getHttpServer())
    > 42 |       .post('/graphql')
         |        ^
      43 |       .send(mutation)
      44 |       .expect(HttpStatus.OK)
      45 |       .expect((response) => {

      at Test.Object.<anonymous>.Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)
      at new Test (../node_modules/supertest/lib/test.js:38:12)
      at Object.obj.<computed> [as post] (../node_modules/supertest/index.js:27:14)
      at Object.<anonymous> (app.e2e-spec.ts:42:8)
import { Test, TestingModule } from '@nestjs/testing'
import { HttpStatus, INestApplication } from "@nestjs/common";
import * as request from 'supertest'
import { AppModule } from '../src/app.module'

describe('AppController (e2e)', () => {
  let app: INestApplication

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
  })

  afterAll(async () => {
    await app.close()
  })

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(HttpStatus.OK)
      .expect('Hello World!')
  })

  it('mutation', async () => {
    const mutation = {
      query: `mutation Create($title: String!) {
        create(title: $title) {
          id,
          title
        }
      }`,
      variables: {
        title: 'Mon programme',
      },
    }
    return request(app.getHttpServer())
      .post('/graphql')
      .send(mutation)
      .expect(HttpStatus.OK)
      .expect( (response) => {
        expect(response.body).toBe({
          id: expect.any(String),
          title: 'Mon programme',
        })
      })
  })
})

무엇이 시험 주자를 막고 있는지 아십니까?

NestJs를 사용하고 있기 때문에 다음을 사용할 필요가 없습니다..end(done)방법을 입력합니다.

PS: 분명히 저는 이 질문에 대해 너무 많은 코드를 작성해야 하고 몇 가지 세부 사항을 추가해야 하지만, 제가 더 말할 수 있는 것이 무엇인지 전혀 모르겠습니다.

아직 완벽한 해결책을 찾지는 못했지만 현재로서는 이 문제를 해결하기 위해 노력하고 있습니다.

jest --config ./test/jest-e2e.json --forceExit

--forceExit 옵션은 openHandles를 어떻게든 죽이고 모든 것을 잠금 해제합니다.하지만, 저는 여전히 그 문제를 다루는 "적절한 방법"을 찾고 있습니다.

이것이 바로 여기 문제입니다.

  it('/ (GET)', () => {
    return request(app.getHttpServer())
                  ^^^^^^^^^^^^^^^^^^^^^
      .get('/')
      .expect(HttpStatus.OK)
      .expect('Hello World!')
  })

서버가 닫히지 않고 테스트 후에도 열려 있습니다.인스턴스(instance)를 참조할 변수를 생성하고 각 검정 후 닫아야 합니다.저는 이것을 알아내려고 몇 시간을 보냈습니다.그리고 이것이 비슷한 문제를 겪고 있는 모든 사람들에게 도움이 되기를 바랍니다.

다음은 수정을 위한 제 아이디어와 함께 사용자 코드의 예입니다.

describe('AppController (e2e)', () => {
  let app: INestApplication
  let server: SERVER_TYPE

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
    // Reference the server instance
    server = app.getHttpServer()
  })

  afterEach(async () => {
    await app.close()
    // Close the server instance after each test
    server.close()
  })

  it('/ (GET)', async () => {
    // Make the request on the server instance
    return await request(server)
      .get('/')
      .expect(HttpStatus.OK)
      .expect('Hello World!')
  })

또한, 당신이 사용하고 있는 것을 알아챘습니다.beforeEach그리고.afterAll당신은 매번 테스트할 때마다 새로운 앱을 만들고 있기 때문에 HTTP 서버에도 문제가 생길 수 있다고 생각합니다.저는 그것에 대해서는 잘 모르겠어요.

import { Test, TestingModule } from '@nestjs/testing'
import { HttpStatus, INestApplication } from "@nestjs/common";
import * as request from 'supertest'
import { AppModule } from '../src/app.module'

beforeEach(() => {
  ...
})

afterEach(() => {
  ...
})

describe('tests', () => {
  ...
})

하지만 그건 제 취향일 뿐이에요, 당신한테 달렸어요.:)

업데이트: 사용하기 위한 것beforeEach것은 아니다.beforeAll글로벌 설정 및 해체가 아닌 각 테스트 전에 서버를 닫아야 하기 때문입니다.

업데이트 2: 다른 방법으로 비동기/대기를 사용하면 요청이 비동기적이며 완료될 때까지 기다리지 않으면 완료되지 않으므로 항상 통과됩니다.

전체 앱을 다시 만드는 중입니다.beforeEach하지만 그것을 부수는 것은 오직.afterAll그 말은 당신이 아마도 도중에 기억을 유출하고 있다는 것을 의미합니다.앱 변수에 새 인스턴스를 할당하고 있지만 가비지 콜렉터가 이전 인스턴스를 지울 수 없도록 하는 숨겨진 참조(예:request함수를 얻었습니다.

바꾸다beforeEach로.beforeAll당신은 가도 좋습니다.

연결과 연결 및 간헐적 오류를 닫았음에도 오류가 발생하는 사용자에게 추가할 수 있습니다.--no-cache --watchAll다음은 전체 구문입니다.

"test": "jest --watchAll --no-cache --detectOpenHandles"

같은 문제가 있었습니다.

    "test:e2e": "jest --config ./test/jest-e2e.json --no-cache --detectOpenHandles",

나는 잘 작동했습니다.

에 에.it사해보다를 써 test그리고 패스done매개 변수로 사용할 수 있습니다.이것은 저에게 효과가 있었습니다.

test('mutation', async (done) => {
    const mutation = {
      query: `mutation Create($title: String!) {
        create(title: $title) {
          id,
          title
        }
      }`,
      variables: {
        title: 'Mon programme',
      },
    }
    const response = request(app.getHttpServer())
      .post('/graphql')
      .send(mutation)
     expect(response).to.be(HttpStatus.Ok)
     done()
  })

매 시험마다

it('the description', (done) => {
        request(app)
          .get('/some-path')
          .end(done);
  });

Toomuchrice4u의 답변이 저에게 도움이 되었습니다.구성 요소가 사용하는 서비스 중 하나에 로그아웃 방법이 있어서 호출했습니다.afterEach다음과 같이:

afterEach(async () => {

await userService.logout();

});

또한 다음 항목을 확인합니다.package.json에 파일을 합니다.scripts을 찾기 test:e2e을 확인하고 키 다 을 값 확 인 제 니 합 거 를--detectOpenHandles 수 ."test:e2e": "jest --config ./test/jest-e2e.json --forceExit"

언급URL : https://stackoverflow.com/questions/68437734/jest-has-detected-the-following-1-open-handle-potentially-keeping-jest-from-exit

반응형