typescript - 用玩笑模拟打字稿界面
问题描述
是否可以用玩笑来模拟打字稿界面?
例如:
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'.
解决方案
我创建了一个库,允许您模拟 TypeScript 接口 - https://github.com/marchaos/jest-mock-extended。
似乎没有库可以在保持完全类型安全的同时干净地做到这一点。它松散地基于这里的讨论 - https://github.com/facebook/jest/issues/7832
推荐阅读
- jenkins - 如何获取下游作业的执行状态码
- c# - dotnet core docker web api没有连接
- python - 我在 Python 耦合 ODE 代码中做错了什么?
- r - R中的中止后台进程/未来
- json - 将 JSON 文件(消息)推送到 RabbitMQ 中的队列
- c# - C# 是否跨平台?
- javascript - Shopify 如何在 GraphiQL 中获取第二页
- windows - 在 Pyspark 中改进 Pandas UDF
- postgresql - psql 没有从 .pgpass 文件中读取密码
- python - 如何将 numpy 数组转换为 wand.image.Image 对象?