【发布时间】: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