Jestjs 被测函数未调用使用Jest创建的部分模块模拟函数

Jestjs 被测函数未调用使用Jest创建的部分模块模拟函数,jestjs,Jestjs,(基于已提供的示例。) 对于下面的模块 // fruit.js export const apple = 'apple'; export const strawberry = () => 'strawberry'; export default () => `banana and ${strawberry()} `; 我想编写一个测试来验证导出的函数是否正确调用了函数草莓。 为了实现这一点,我尝试了以下测试 // partial_mock.js import defaultEx

(基于已提供的示例。) 对于下面的模块

// fruit.js
export const apple = 'apple';

export const strawberry = () => 'strawberry';

export default () => `banana and ${strawberry()} `;
我想编写一个测试来验证导出的函数是否正确调用了函数草莓。 为了实现这一点,我尝试了以下测试

// partial_mock.js
import defaultExport, { strawberry } from '../fruit';

jest.mock('../fruit', () => {
  const originalModule = require.requireActual('../fruit');
  const mockedModule = jest.genMockFromModule('../fruit');

  // Mock the exported 'strawberry' function.
  return Object.assign({}, mockedModule, originalModule, {
    strawberry: jest.fn(() => 'mocked strawberry'),
  });
});

it('does a partial mock', () => {
  expect(strawberry()).toBe('mocked strawberry');

  const defaultExportResult = defaultExport();
  expect(defaultExportResult).toBe('banana and mocked strawberry');
});
但是,不调用模拟函数,而是调用实际函数

 × does a partial mock (21ms)

  ● does a partial mock

    expect(received).toBe(expected) // Object.is equality

    Expected: "banana and mocked strawberry"
    Received: "banana and strawberry "
这是预期的吗


我的考试有效吗?我在测试中遗漏了什么吗?

发生的事情是,当Jest导入
fruit.js
以从中生成模拟时,默认导出中的匿名函数已经在其闭包中获取了对实际草莓的引用

因此,Jest所做的一切就是对以后导入它的任何其他模块(例如,您的测试套件)进行模拟

本文介绍了一些解决此问题的方法:

我的建议是在运用任何解决方案之前考虑重构你的逻辑:

  • fruit.js
    中的一些函数是作为实现细节还是用于分解逻辑?也许你可以像对待私有类方法一样对待它们,并通过
    defaultExport
    本身来测试它们

  • 如果它们的逻辑是如此独立,以至于需要在测试之间进行模拟,那么函数是否应该驻留在单独的模块中