【问题标题】:typescript interface extends mock打字稿接口扩展模拟
【发布时间】:2019-01-20 14:16:37
【问题描述】:

我有一个打字稿接口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>'.

在测试中将此接口模拟注入方法的正确方法是什么?

【问题讨论】:

    标签: javascript typescript jestjs typemoq


    【解决方案1】:

    为什么要发明轮子? Jest 有一个用附加方法“装饰”给定接口的接口。

    例如:

    interface IRequest {
       req: string;
    }
    
    requestMock: jest.Mocked<IRequest>;
    

    requestMock 将具有 IRequest 接口 + 模拟接口。

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

    【讨论】:

    • 它没有来自Request 的所有值类型来自express。这个类型有几个在它下面输入的值。所以很难用正确的类型来指定它们中的每一个
    【解决方案2】:

    我能够通过以下方式克服这个问题

    const cRequestStub= <cRequest> {};
    

    而且现在可以根据需要选择性地注入参数而不会出现任何错误

    const cRequestStub= <cRequest> {user: undefined}; or
    const cRequestStub= <cRequest> {context: {ID: '', user: '', nonUser: ''}};
    
    await classObj.getData(cRequestStub, expRespMock);
    

    【讨论】:

      猜你喜欢
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      相关资源
      最近更新 更多