我有一个 typescript 接口(interface)cRequest
,它作为类方法中的类型传递。
该接口(interface)还扩展了 express
请求类型。在 jest
或 typemoq
中模拟这个的正确方法是什么?
import { Request } from 'express';
import { User } from '.';
export interface cRequest extends Request {
context: {
ID?: string;
user?: string;
nonUser?: string;
};
user?: User;
}
export default cRequest;
这在类方法中使用如下
import { Response } from 'express';
public getData = async (req: cRequest, res: Response) => {}
如果我尝试按如下方式测试它,它会失败
const expRespMock: TypeMoq.IMock<Response> = TypeMoq.Mock.ofType<Response>();
const cReqMock: TypeMoq.IMock<cRequest> = TypeMoq.Mock.ofType<cRequest>();
await classObj.getData(cReqMock, expRespMock);
带有以下消息
Argument of type 'IMock<cRequest>' is not assignable to parameter of type 'cRequest'.
Property 'context' is missing in type 'IMock<cRequest>'.
将此接口(interface)模拟注入(inject)测试方法的正确方法是什么?
最佳答案
我能够如下解决这个问题
const cRequestStub= <cRequest> {};
而且现在可以根据需要有选择地注入(inject)参数而不会出现任何错误
const cRequestStub= <cRequest> {user: undefined}; or
const cRequestStub= <cRequest> {context: {ID: '', user: '', nonUser: ''}};
await classObj.getData(cRequestStub, expRespMock);
关于javascript - typescript 接口(interface)扩展模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51829292/