【问题标题】:How to strongly type jest mocks如何强输入笑话模拟
【发布时间】:2019-07-23 07:55:57
【问题描述】:

我想强烈键入我的笑话。在某种程度上,我可以让它工作,但是当一个类有私有属性时,我就卡住了。

另外一个问题,当我使用模拟时(我目前使用的方式),返回类型是原始类型,但是当我必须访问 Jest 添加的任何方法时,我必须对其进行类型转换,所以jest.Mock 才能访问一个方法.有一个更好的方法吗?我尝试过使用jest.Mockjest.Mockedjest.MockInstance

如果有人能指出我正确的方向,那就太好了!

class MyTest {
    constructor(private readonly msg: string) {}

    public foo(): string {
        return this.msg;
    }
}

const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(() => ({
    msg: 'private',
    foo: jest.fn().mockReturnValue('aaa'),
}));
// Results in error:
// Type '{ msg: string; foo: Mock<any, any>; }' is not assignable to type 'MyTest'.
// Property 'msg' is private in type 'MyTest' but not in type '{ msg: string; foo: Mock<any, any>; }'

const myTestMockInstance: MyTest = new myTestMock('a');
console.log(myTestMockInstance.foo()); // --> aaa

// Accessing jest mock methods:
(<jest.Mock>myTestMockInstance).mockClear(); // <-- can this be done without type casting

肮脏的解决方法:

const myTestMock: jest.Mock<MyTest, [string]> = jest.fn<MyTest, [string]>(
    // Cast to any to satisfy TS
    (): any => ({
        msg: 'private',
        foo: jest.fn().mockReturnValue('aaa'),
    })
);

【问题讨论】:

  • 私有属性有什么问题? IMO 你应该只模拟(和测试)公共接口。你看过这篇文章吗? patrickdesjardins.com/blog/…
  • @KimKern 问题是打字稿抛出错误,因为模拟不包含私有属性,所以我的模拟与我试图模拟的类型不匹配。
  • 感谢您的链接,有趣的文章虽然我认为这是一种解决方法,但它可能是目前最好的选择。我希望 jest 已经有办法做到这一点,而不是创建自己的别名。
  • 是的,这绝对只是一种解决方法。 :/我正在使用它,但我也遇到了这种方法的问题。但是由于 jest 正在为下一个主要版本迁移到 typescript,我希望这会变得更好。另见github.com/facebook/jest/issues/7832

标签: typescript jestjs typescript-typings ts-jest


【解决方案1】:

有一个库可以帮助您在 Typescript with Jest 中使用强类型模拟:jest-mock-extended

我不确定您是否应该访问模拟的私有属性。正如 Kim Kern 所说,您应该只对被测单元的依赖项的公共接口感兴趣。

jest-mock-extended 包含一个mock() 方法,该方法返回一个MockProxy,允许您访问.mockReturnValue() 等。

import { mock } from "jest-mock-extended";

interface WidgetService {
  listMyWidgets(): { id: string }[];
};

const mockedService = mock<WidgetService>();
mockedService.listMyWidgets.mockReturnValue([{ id: 'widget-1' }]);

【讨论】:

    【解决方案2】:
    1. 有一个帮助器可以生成类型:看ts-jest
    1. 通常您应该测试公共接口,而不是实现。您可以将该逻辑提取到公共接口(可能是另一个提供该接口的类),而不是测试私有方法

    【讨论】:

    猜你喜欢
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2018-12-31
    • 2019-03-03
    相关资源
    最近更新 更多