如何强力输入笑话模拟

Mic*_*ael 11 typescript jestjs typescript-typings ts-jest

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

另一个问题是,当我使用模拟(当前使用的方式)时,返回类型是原始类型,但是当我必须访问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
Run Code Online (Sandbox Code Playgroud)

变通方法:

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

小智 7

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

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

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

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

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

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


Yoz*_*ozi 2

  1. 有一个帮助器可以创建类型:look ts-jest
  1. 通常你应该测试公共接口,而不是实现。您可以将该逻辑提取到公共接口(也许是提供该接口的另一个类),而不是测试私有方法

  • ts-jest 的有效示例位于 /sf/answers/4415245131/ (3认同)