Mak*_*una 1 integration-testing node.js typescript jestjs nestjs
我目前正在尝试获取“超级测试”请求的响应对象。
\n如果我在没有等待的情况下调用 get,我会得到一个 httpCode 200,但没有正文:
\nimport { Test, TestingModule } from '@nestjs/testing';\n\nimport { AuthModule } from './auth.module';\nimport { INestApplication } from '@nestjs/common';\nimport * as request from 'supertest';\n\ndescribe('AuthService', () => {\n let app: INestApplication;\n beforeAll(async () => {\n const module: TestingModule = await Test.createTestingModule({\n providers: [AuthModule]\n}).compile();\napp = module.createNestApplication();\nawait app.init();\n});\n\nit('should be defined', async () => {\nconst res = request(app.getHttpServer())\n .get('/')\n .expect(200);\n\n});\n\nafterAll(async () => {\n app.close();\n});\n});\n
Run Code Online (Sandbox Code Playgroud)\nJest 给了我以下输出。但我无法引用 res.body
\n AuthService\n\xe2\x88\x9a should be defined (5ms)\n\nTest Suites: 1 passed, 1 total\nTests: 1 passed, 1 total\nSnapshots: 0 total\nTime: 15.961s, estimated 16s\n
Run Code Online (Sandbox Code Playgroud)\n现在,如果我将 get 调用更改为异步调用:
\n it('should be defined', async () => {\nconst res = await request(app.getHttpServer())\n .get('/')\n .expect(200);\n\n});\n
Run Code Online (Sandbox Code Playgroud)\n我得到失败测试结果:
\n AuthService\n\xc3\x97 should be defined (35ms)\n\n\xe2\x97\x8f AuthService \xe2\x80\xba should be defined\n\nexpected 200 "OK", got 404 "Not Found"\n\n at Test.Object.<anonymous>.Test._assertStatus (node_modules/supertest/lib/test.js:268:12)\n at Test.Object.<anonymous>.Test._assertFunction (node_modules/supertest/lib/test.js:283:11)\n at Test.Object.<anonymous>.Test.assert (node_modules/supertest/lib/test.js:173:18)\n at Server.localAssert (node_modules/supertest/lib/test.js:131:12)\n\nTest Suites: 1 failed, 1 total\nTests: 1 failed, 1 total\nSnapshots: 0 total\n
Run Code Online (Sandbox Code Playgroud)\n如果没有异步调用,我无法引用正文。但我每次都会在同一个 get 函数上得到 404 错误。只是使用await 进行异步调用。
\n没有异步的测试通过只是因为测试在断言expect(200)
运行之前完成。在这两种情况下,调用/
都会返回 404 错误。
主要问题是您将模块声明为提供者,而不是导入它:
await Test.createTestingModule({
// should be imports instead of providers
providers: [AuthModule]
})
Run Code Online (Sandbox Code Playgroud)
为什么要AuthModule
与应用程序的其余部分分开设置?我建议您单独测试您的单元测试(仅包括经过测试的提供程序,模拟其他所有内容)并在 e2e 测试中测试您的整个应用程序(如有必要,仅模拟应用程序的不同部分,例如,对第三个的 API 调用)聚会服务);有关更多详细信息,请参阅此线程。
我建议改为导入AppModule
:
const module: TestingModule = await Test.createTestingModule({
imports: [AppModule]
}).compile();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4693 次 |
最近记录: |