如何使用带Typescript的express在Mocha中模拟“请求”?当前的解决方案如下:
describe("Authorization middleware", () => {
it("Fails when no authorization header", () => {
const req = {
get: () => {
return null;
},
};
expect(isAuth(req as Request, {}, () => {}));
});
});
出现错误Conversion of type '{ get: () => null; }' to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
强制使用“未知”类型是解决此问题的唯一方法吗?
1条答案
按热度按时间4xrmg8kj1#
您可以使用node-mocks-http包为
express
路由功能创建request
和response
对象的模型。例如
httpMocks.createRequest()
API返回值为MockRequest
类型,其泛型参数受Request
类型约束,Request
类型是MockRequest
类型的子集,因此与Request
类型匹配。