我正在使用 Jest 对我的 NestJS 应用程序进行端到端测试。这运行良好,但我现在想要做一些测试,验证例程是否如我所料那样失败。
例如,我可以进行如下标准测试:
describe('Item Service (e2e)', () => {
let app: INestApplication;
const BaseUriPath:string = '/v1/item';
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('./inquiry (POST) header field validation ', async done => {
const RequestBody = `
{
"cardNumber":"1234567890123",
"cardCode":"",
"entryMode":"scan",
"date":"2018-08-16T12:04:13-04:00",
"sequenceId":"123456"
}
`;
const ResponseData = await request(app.getHttpServer())
.post(`${BaseUriPath}/inquiry`)
.set('Accept-Language', 'en')
.set('Content-Type', 'application/json')
.set('User-Agent', 'OurApp')
.set('traceabilityId', 'a90baa34-970b-11eb-a8b3-0242ac130003')
.set('messageId', 'a90baa34-970b-11eb-a8b3-0242ac130003')
.set('operationMode', 'PRODUCTION')
.send(RequestBody);
expect(ResponseData.status).toBe(200);
expect(ResponseData.headers['content-type']).toContain('json');
...
done(); // Call this to finish the test
});
});
这工作正常,并调用我的 API,按照我的预期进行检查。我的类使用类验证器来强制定义(@IsString、@IsUUID 等)。所有这些都有效。现在的问题是我在某些请求中需要更多的标头字段。然后我希望能够做的是创建一个例程来省略一个例程,并确保验证仍然是返回错误。我可以复制相同的测试,并注释掉 1 .set() 但这对我来说似乎是多余的。
我希望能够遍历数组或其他东西,而不是根据数字进行设置。为此,我需要能够在回调中创建请求对象。
const RequestObj = request(app.getHttpServer());
RequestObj.post(`${BaseUriPath}/inquiry`)
.set('Accept-Language', 'en')
.set('Content-Type', 'application/json')
...
;
或
RequestObj.post(`${BaseUriPath}/inquiry`);
RequestObj.set('Accept-Language', 'en')
RequestObj.set('Content-Type', 'application/json')
...
;
然后使用上面的对象,调用类似:
const ResponseData = await RequestObj;
然后就可以进行正常的测试操作了。
expect(ResponseData.status).toBe(200);
expect(ResponseData.headers['content-type']).toContain('json');
...
done(); // Call this to finish the test
我不知道如何构建 RequestObj 以便我可以调用我的实际 API。