用玩笑嘲笑/插入Typescript接口

问题描述 投票:3回答:2

是否可以通过Jest或其他模拟/存根库对Typescript接口进行模拟或存根?

例如,我想模拟ExpressJS的Response对象:export interface Response extends http.ServerResponse, Express.Response

而不是手工制作实现我正在寻找的库来为我完成所有方法的对象。

typescript unit-testing jestjs
2个回答
2
投票

我最终为此使用了类型断言,这有点hack。像这样:

const res = {} as Express.Response;

有关type assertions is available here的一些信息:

类型断言是一种告诉编译器“相信我,我知道我在做什么的方法。”类型断言就像其他语言中的类型转换一样,但是不执行数据的特殊检查或重组。它对运行时间没有影响,仅由编译器使用。 TypeScript假定您(程序员)已经执行了所需的任何特殊检查。


1
投票

[来自@ n00b的启发,但更为完整:

首先对未知使用类型断言,然后对所需的接口使用类型断言,以使编译器接受它。

然后模拟您需要的东西(在此示例中,myFunction only调用Response.send,您将或多或少地模拟)]

一个完整的例子,可以在__tests__/myFunctionTest.ts文件中:

import * as functions from 'firebase-functions';
import * as myfunction from '../src/myFunction';
test('it should do the thing', () => {
  const req = { } as unknown;
  const mockReq = req as functions.https.Request;
  const res = { send: jest.fn() } as unknown;
  const mockRes = res as functions.Response;
  myFunction.doTheThing(mockReq, mockRes);
  expect(mockRes.send).toBeCalledWith("{ 'status': 'the thing is done' }";
});

src/myFunction.ts文件为:

import * as functions from 'firebase-functions';

export const doTheThing = functions.https.onRequest((request, response) => {
  response.send("{ 'status': 'the thing is done' }");
});

注意,这与Express所需的模拟非常接近-firebase函数请求/响应建立在这些Typescript接口上,因此该策略应适用。

© www.soinside.com 2019 - 2024. All rights reserved.