serverless-offline 插件 在本地运行,并且仅接收带有一些查询参数的 GET 请求。我正在使用 Jest 和 Supertest 编写集成测试,如下所示:
import request from 'supertest';
describe('User position handler', () => {
it('should return history', () => {
const server = request('http://0.0.0.0:4000');
return server
.get(`/local/position?type=month&period=3`)
.expect(200)
.expect((response) => {
console.log('RESPONSE', response);
expect(response.body).toHaveLength(3);
});
});
});
问题是,当我使用收集覆盖率选项运行 Jest 时,通过 Supertest 发送的请求到达的代码不会在指标中计算。运行jest --collectCoverage
结果是:问题是,我知道,例如,正在达到
infra/handlers/user-position.ts
并覆盖了超过 0% 的语句,但覆盖率指标并未按预期显示。另外,我知道在流程的某个点正在达到
user-monthly-position.service.impl.ts
,因为该服务负责从外部服务返回数据,并且 Supertest 的响应正在返回数据。绿线来自单元测试覆盖的文件,这些文件仅使用 Jest(显然不是 Supertest)我知道当将 Supertest 与 Express 框架一起使用时,我可以传递 Express 应用程序的实例。到
request
函数。这样我认为 Jest 可以“检查”或“检测”函数调用堆栈来测量覆盖率(下面的代码示例)。但是我怎样才能通过正在运行的
serverless-offline
Lambda 的 URL 来完成同样的操作呢?
const request = require('supertest');
const assert = require('assert');
const express = require('express');
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'john' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});
这是我的处理函数的代码:
export default async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {
await cacheService.bootstrapCache();
const userMonthlyPositionService = new UserMonthlyPositionServiceImpl(
cacheService.connectionPool,
);
const getUserMonthlyPositionHistory = new GetUserMonthlyPositionHistory(
userMonthlyPositionService,
);
const result = await getUserMonthlyPositionHistory.execute({
cblc: 999999,
period: 3,
type: 'month',
});
return buildResponse(200, result);
};
我的问题是:如何使用 Supertest 和无服务器框架从 Jest 收集正确的代码覆盖率指标?我是不是忘记了一个细节?谢谢!