打字稿界面扩展了模拟



我有一个打字稿接口cRequest它作为类方法中的类型传递。 此接口还扩展express请求类型。在jesttypemoq中嘲笑它的正确方法是什么?

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 接口 + 模拟接口。

了解新笑话类型的最简单方法是检查@types/jest库的源代码,例如,我已经检查了jest.spyOn的返回类型,并从中了解了jest.Mocked<>

最新更新