【问题标题】:NestJs and Jest: await request throws 404NestJs 和 Jest:等待请求抛出 404
【发布时间】:2020-12-12 23:34:02
【问题描述】:

我目前正在尝试获取“超级测试”请求的响应对象。

如果我在没有等待的情况下调用 get,我会得到一个 httpCode 200,但没有正文:

import { Test, TestingModule } from '@nestjs/testing';

import { AuthModule } from './auth.module';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';

describe('AuthService', () => {
   let app: INestApplication;
   beforeAll(async () => {
     const module: TestingModule = await Test.createTestingModule({
  providers: [AuthModule]
}).compile();
app = module.createNestApplication();
await app.init();
});

it('should be defined', async () => {
const res = request(app.getHttpServer())
  .get('/')
  .expect(200);

});

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

Jest 给了我以下输出。但我不能参考 res.body

  AuthService
√ should be defined (5ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.961s, estimated 16s

现在,如果我将 get 调用更改为异步调用:

  it('should be defined', async () => {
const res = await request(app.getHttpServer())
  .get('/')
  .expect(200);

});

我得到一个失败的测试结果:

  AuthService
× should be defined (35ms)

● AuthService › should be defined

expected 200 "OK", got 404 "Not Found"

  at Test.Object.<anonymous>.Test._assertStatus (node_modules/supertest/lib/test.js:268:12)
  at Test.Object.<anonymous>.Test._assertFunction (node_modules/supertest/lib/test.js:283:11)
  at Test.Object.<anonymous>.Test.assert (node_modules/supertest/lib/test.js:173:18)
  at Server.localAssert (node_modules/supertest/lib/test.js:131:12)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total

没有异步调用,我无法引用正文。但我每次都得到一个 404,在同一个 get 函数上。刚刚使用 await 进行异步调用。

【问题讨论】:

    标签: node.js typescript jestjs integration-testing nestjs


    【解决方案1】:

    没有异步的测试通过只是因为测试在您的断言 expect(200) 运行之前完成。在这两种情况下,调用 / 都会返回 404 错误。

    主要问题是您将模块声明为提供程序,而不是导入它:

    await Test.createTestingModule({
      // should be imports instead of providers
      providers: [AuthModule]
    })
    

    为什么要将AuthModule 与应用程序的其他部分分开设置?我建议您单独测试您的单元测试(仅包括被测试的提供程序,模拟其他所有内容)并在 e2e 测试中测试您的整个应用程序(仅在必要时模拟应用程序的不同部分,例如,对 3rd- 的 API 调用派对服务);有关详细信息,请参阅this thread

    我建议改为导入 AppModule

    const module: TestingModule = await Test.createTestingModule({
      imports: [AppModule]
    }).compile();
    

    【讨论】:

    • 我按照你说的做了。但是现在,我收到以下消息:无法从 'config.service.ts' 中找到模块 '@project/module-dto' 但是我已经在 config.service.ts 中导入了相应的文件
    • 您是否导入了 AppModule?如果没有看到您的代码,很难提供帮助。不过,现在的问题似乎非常不同。最简单的方法是您打开一个新问题并包含代码的所有相关位,例如。 g.,配置服务/模块。
    • 谢谢,我会的。
    猜你喜欢
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    相关资源
    最近更新 更多