typescript 用玩笑模拟打字稿界面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52122234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:37:58  来源:igfitidea点击:

Mock a typescript interface with jest

typescriptmockingjestjs

提问by Cuthbert

Is it possible to mock a typescript interface with jest?

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

For example:

例如:

import { IMultiplier } from "./IMultiplier";

export class Math {
  multiplier: IMultiplier;

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

Then in a test:

然后在测试中:

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);
    });
});

I've tried to create a mock object to satisfy this a number of ways, but none work. For example assigning it this mock:

我试图创建一个模拟对象来满足这一点,但没有一种方法。例如分配它这个模拟:

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

Will produce something along the lines of:

将产生以下方面的东西:

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

采纳答案by Brian Adams

The mock just needs to have the same shapeas the interface.

模拟只需要与界面具有相同的形状

(from the docs: One of TypeScript's core principles is that type-checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”.)

(来自文档TypeScript 的核心原则之一是类型检查侧重于值的形状。这有时称为“鸭子类型”或“结构子类型”。

So mathlib.multiplierjust needs to be assigned to an object that conforms to IMultiplier.

所以mathlib.multiplier只需要分配给一个符合IMultiplier.

I'm guessing that IMultiplierfrom the example looks something like this:

我猜这个IMultiplier例子看起来像这样:

interface IMultiplier {
  multiply(a: number, b: number): number
}

So the example test will work fine by changing the line in question to this:

因此,通过将有问题的行更改为以下内容,示例测试将正常工作:

mathlib.multiplier = {
  multiply: jest.fn((a, b) => a * b)
};

回答by marchaos

I created a library which allows you to mock out TypeScript interfaces - https://github.com/marchaos/jest-mock-extended.

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

There didn't seem to be libs that does this cleanly whilst keeping full type safety. It's based loosely on the discussion here -https://github.com/facebook/jest/issues/7832

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