NestJS SuperTest Jest 在测试运行完成后一秒没有退出

问题描述 投票:0回答:2

我想从主体中保存一些数据,并在测试中的下一个请求中使用它。我正在做一个post请求并返回一个id。我想用这个 id 在其他测试中获取数据。

我的代码如下所示:

it('/auth/register (POST)', async () => {
   const test = await request(app.getHttpServer())
      .post('/api/auth/register')
      .send({username: "Zoe"})
      .expect(201)
   token = test.body.token
})

令牌正在设置并且代码正在运行,但是我的玩笑测试不会停止,我会收到错误:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.

我知道我可以强制退出,但我想干净地完成并理解问题。

当我执行笑话返回方法时,它正在工作..但是我不知道如何将主体存储在某处..

it('/auth/register (POST)', () => {
   request(app.getHttpServer())
      .post('/api/auth/register')
      .send({username: "Zoe"})
      .expect(201)
})
javascript testing jestjs nestjs supertest
2个回答
0
投票

我通过在应用程序关闭时关闭数据库连接解决了这个问题

import { Module } from '@nestjs/common';
import { getConnection } from 'typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DatabaseModule } from './database/database.module';
import { FormsModule } from './forms/forms.module';

@Module({
  imports: [
    DatabaseModule,
    FormsModule, 
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  onApplicationShutdown(){
    getConnection().close();
  }
}

```

0
投票

我在使用 TypeORM 时遇到了同样的问题。要调试,您可以尝试设置标志

--detectOpenHandles

像这样:

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

npm run test:e2e --detectOpenHandles

那么就可以和你的数据库或者redis的连接有关。例如,我使用 TypeORM,帮助我解决问题的是:

// my.e2e-spec.ts

import { DataSource } from 'typeorm';
...

describe('MyController (e2e)', () => {
  let app: INestApplication;
  let connection: DataSource;

  beforeEach(async () => {
  ...
    app = moduleFixture.createNestApplication();
    connection = moduleFixture.get<DataSource>(DataSource);
    await app.init();
  });

  
  });

  afterAll(async () => {
    await connection.destroy(); // <- this
    await app.close(); // <- and that
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.