NestJS SuperTest Jest在测试运行完成后一秒内未退出

sd2nnvve  于 8个月前  发布在  Jest
关注(0)|答案(2)|浏览(74)

我想保存一个body中的一些数据,并在测试中的下一个请求中使用它。我正在执行一个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
})

字符串
token正在设置,代码正在运行,但是我的jest测试不会停止,我会得到错误:

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.


我知道我可以执行forceExit,但我想干净地执行它并理解问题。
当我做的jest返回方法,它的工作。.然而有Idk如何存储身体的地方。.

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

tuwxkamq

tuwxkamq1#

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

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();
  }
}
字符串
jrcvhitl

jrcvhitl2#

我在使用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
  });
});

相关问题