javascript - typescript 接口(interface)扩展模拟

标签 javascript typescript jestjs typemoq

我有一个 typescript 接口(interface)cRequest,它作为类方法中的类型传递。 该接口(interface)还扩展了 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>'.

将此接口(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/

相关文章:

javascript - 从冗长的字符串中获取句子数组,每个数组 [index] 不超过最大字符长度

javascript - 在 NextJs 的服务器端代码中访问静态资源?

typescript - 为什么在尝试建立关系时 joinColumns 未定义?

jestjs - Jest 全局变量持续存在

reactjs - 如何使用 Jest 模拟 React 组件静态方法

reactjs - Jest - 测试使用react-router的组件

javascript - 为什么 parseJSON 将我的 JavaScript 对象包装在一个新对象中?

javascript - 如何使用 blueprintjs/table 渲染表格

javascript - 如何用后面的vb.net代码读取HTML5 textarea文本

angularjs - 如何在 typescript 中使用谷歌分析并访问数据层