簡體   English   中英

打字稿接口擴展模擬

[英]typescript interface extends mock

我有一個打字稿接口cRequest ,它在類方法中作為類型傳遞。 此接口還擴展了express Request 類型。 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 接口 + 模擬接口。

了解新 jest 類型的最簡單方法是檢查@types/jest庫的源代碼,例如我檢查過jest.spyOn的返回類型,並從中了解了jest.Mocked<> .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM