【问题标题】:Mocking multiple named exports in jest.mock(moduleName, factory) factory function在 jest.mock(moduleName, factory) 工厂函数中模拟多个命名导出
【发布时间】:2018-06-17 23:49:48
【问题描述】:

我一直在一个小项目中使用 Jest,但在使用 Jest 模拟时遇到了问题。我有一个导出命名自定义错误构造函数的实用程序文件。我需要在我的测试文件中模拟这些函数。我不想使用 Jest 文档中显示的手动模拟技术(即,将模拟文件放在 __mocks__ 中),而是我想在测试文件中定义模拟。我在我的测试文件中尝试这样的事情:

const errorMock = () => {
  return {
    configNotFoundError: jest.fn(() => new Error()),
    invalidJSONError: () => jest.fn(() => new Error()),
  }
};

jest.mock('./error', errorMock);

const { configNotFoundError, invalidJSONError } = require('./error');

但我收到以下错误:

babel-plugin-jest-hoist: The second argument of `jest.mock` 
must be an inline function.

有人可以帮我理解我做错了什么吗?

【问题讨论】:

    标签: javascript node.js unit-testing jestjs babel-jest


    【解决方案1】:

    我最近在命名导出方面遇到了类似的问题。 根据docsjest.mock 调用被提升到测试的顶部,随后在您定义errorMock 之前执行。函数似乎被提升到这些调用之上。试试:

    function errorMock() {
      return {
        configNotFoundError: jest.fn(() => new Error()),
        invalidJSONError: () => jest.fn(() => new Error()),
      }
    };
    
    jest.mock('./error', errorMock);
    
    const { configNotFoundError, invalidJSONError } = require('./error');
    

    【讨论】:

    • 非常感谢@Lesbaa,很好的回答!
    • 这可能很危险,因为您很容易在函数中使用外部上下文。最好按照错误的建议保持内联。
    猜你喜欢
    • 2021-07-17
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2018-11-30
    相关资源
    最近更新 更多