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
Mock a typescript interface with jest
提问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.multiplier
just needs to be assigned to an object that conforms to IMultiplier
.
所以mathlib.multiplier
只需要分配给一个符合IMultiplier
.
I'm guessing that IMultiplier
from 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