用玩笑模拟/存根打字稿界面

n00*_*00b 6 unit-testing typescript jestjs

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

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

而不是手工制作一个实现所有方法的对象,我正在寻找一个库来为我做这件事。

n00*_*00b 7

我最终为它使用了类型断言,这有点小技巧。所以像:

const res = {} as Express.Response;
Run Code Online (Sandbox Code Playgroud)

此处提供了有关类型断言的一些信息,其中说:

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


Mik*_*rdy 6

受到@n00b 的启发,但更完整:

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

然后模拟你需要的东西(在这个例子中,myFunction调用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' }";
});
Run Code Online (Sandbox Code Playgroud)

src/myFunction.ts文件将是:

import * as functions from 'firebase-functions';

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

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