[英]typescript interface extends mock
我有一个打字稿接口cRequest
,它在类方法中作为类型传递。 此接口还扩展了express
Request 类型。 在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>'.
在测试中将此接口模拟注入方法的正确方法是什么?
所以我能够克服这个问题如下
const cRequestStub= <cRequest> {};
而且现在可以根据需要选择性地注入参数而不会出现任何错误
const cRequestStub= <cRequest> {user: undefined}; or
const cRequestStub= <cRequest> {context: {ID: '', user: '', nonUser: ''}};
await classObj.getData(cRequestStub, expRespMock);
为什么要发明轮子? Jest 有一个接口,它用附加的方法“装饰”给定的接口。
例如:
interface IRequest {
req: string;
}
requestMock: jest.Mocked<IRequest>;
requestMock 将具有 IRequest 接口 + 模拟接口。
了解新 jest 类型的最简单方法是检查@types/jest
库的源代码,例如我检查过jest.spyOn
的返回类型,并从中了解了jest.Mocked<>
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.