typescript - 如何强输入 Jest 模拟

标签 typescript jestjs typescript-typings ts-jest

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

另一个问题,当我使用模拟时(我目前使用的方式),返回类型是原始类型,但是当我必须访问 Jest 添加的任何方法时,我必须对其进行类型转换,所以 jest.Mock访问方法。有一个更好的方法吗?我尝试过使用 jest.Mock , jest.Mocked , jest.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'),
    })
);

最佳答案

有一个库可以帮助您在 Typescript with Jest 中使用强类型模拟:jest-mock-extended
我不确定您是否应该访问模拟的私有(private)属性。正如 Kim Kern 所说,您应该只对被测单元的依赖项的公共(public)接口(interface)感兴趣。
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' }]);

关于typescript - 如何强输入 Jest 模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54941990/

相关文章:

visual-studio-2013 - typescript 1.0 map 文件不加载

javascript - 在用 Jest 测试之前等待 React 组件状态更新

javascript - angular 的 definelytyped 不识别 JQueryStatic

typescript - 根据 typescript 中的构造函数参数重载类属性

jquery - 如何获取特定版本的 Jquery(例如 3.2.1)的 TypeScript 定义文件?

typescript - VS 代码 : enable javascript intellisense in typescript project

Angular:如何重置 matChipList 输入字段和 Google Recaptcha?

Angular 2 --aot 导致 AnimationEntryMetadata 失败

typescript - 带有模块分辨率的 typescript 的 Jest 设置

不使用 Vue CLI 测试纯 JavaScript Vue 组件