【问题标题】:How to resolve Flow type error from Jest mocking如何解决来自 Jest 模拟的流类型错误
【发布时间】:2017-12-14 21:15:50
【问题描述】:

我正在使用 Jest 模拟模块中的某些功能并以下列方式进行测试:

jest.mock("module", () => ({
  funcOne: jest.fn(),
  funcTwo: jest.fn(),
  ...
}));

import {funcOne, funcTwo, ...} from "module";

test("something when funcOne returns 'foo'", () => {
  funcOne.mockImplementation(() => 'foo');  // <- Flow error
  expect(...)
});

test("that same thing when funcOne returns 'bar'", () => {
  funcOne.mockImplementation(() => 'bar');  // <- Flow error
  expect(...)
});

如何阻止 Flow 报告 property 'mockImplementation' not found in statics of function 错误没有错误抑制(例如 $FlowFixMe)?

我了解问题出在模块中定义的函数不是 Jest-mocked 函数,并且就 Flow 而言,不包含 mockImplementationmockReset 等方法。

【问题讨论】:

标签: javascript jestjs flowtype


【解决方案1】:

我建议使用JestMockFn 类型,而不是使用any 来抑制错误。这是一个相关问题:https://github.com/flow-typed/flow-typed/issues/291

示例(从上面的链接复制):

import ajax from '../../js/comm/ajax';
jest.mock('../../js/comm/ajax', () => {
  return {
    default: jest.fn(),
  }
});
const mockAjax: JestMockFn<[string], Promise<{body: {}}>> = ajax;
describe('ConfigurationProvider', () => {
  it('calling the fetchConfig() should return a promise', () => {
    const expectedCfg = {x:'y'};
    mockAjax.mockReturnValueOnce(
      Promise.resolve({body:expectedCfg})
    );
    ...
  });
});

这是在最新的 jest 版本中定义类型的方式:https://github.com/flow-typed/flow-typed/blob/master/definitions/npm/jest_v25.x.x/flow_v0.104.x-/jest_v25.x.x.js

请注意,类型是全局的,不必导入(我认为这是一个不幸的决定,但这是一个不同的主题)。

【讨论】:

  • 这对我有用,但我必须这样做 const mockCookieManagerGet: JestMockFn&lt;[string], Promise&lt;{ [string]: string }&gt;&gt; = (CookieManager.get: any);。我真的不明白为什么;它说CookieManager.get 是一个不精确的函数类型,因此与精确的JestMockFn 类型不匹配。不过在调用它时最好有这种类型的信息。
【解决方案2】:

您也可以放松内联类型约束:

test("something when funcOne returns 'foo'", () => {
    (funcOne: any).mockImplementation(() => 'foo');  // mo more flow errors!
    ...
});

【讨论】:

    【解决方案3】:

    感谢 Andrew Haines,您发布的 related issue 上的 cmets 提供了解决方案。我对以下内容感到满意:

    const mock = (mockFn: any) => mockFn;
    
    test("something when funcOne returns 'foo'", () => {
        mock(funcOne).mockImplementation(() => 'foo');  // mo more flow errors!
        ...
    });
    

    【讨论】:

      猜你喜欢
      • 2017-05-01
      • 2020-02-24
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多