首页 > 解决方案 > 用玩笑模拟打字稿界面

问题描述

是否可以用玩笑来模拟打字稿界面?

例如:

import { IMultiplier } from "./IMultiplier";

export class Math {
  multiplier: IMultiplier;

  public multiply (a: number, b: number) {
    return this.multiplier.multiply(a, b);
  }
}

然后在测试中:

import { Math } from "../src/Math";
import { IMultiplier } from "../src/IMultiplier";

describe("Math", () => {

    it("can multiply", () => {
        let mathlib = new Math();
        mathlib.multiplier = // <--- assign this property a mock
        let result = mathlib.multiply(10, 2);
        expect(result).toEqual(20);
    });
});

我试图通过多种方式创建一个模拟对象来满足这一点,但都没有奏效。例如分配它这个模拟:

let multiplierMock = jest.fn(() => ({ multiply: jest.fn() }));

将产生以下内容:

Error - Type 'Mock<{ multiply: Mock<{}>; }>' is not assignable to type 'IMultiplier'.

标签: typescriptmockingjestjs

解决方案


我创建了一个库,允许您模拟 TypeScript 接口 - https://github.com/marchaos/jest-mock-extended

似乎没有库可以在保持完全类型安全的同时干净地做到这一点。它松散地基于这里的讨论 - https://github.com/facebook/jest/issues/7832


推荐阅读