如果来自同一模块,则无法模拟依赖函数

Unable to mock a dependent function if its from the same module

我一直在尝试调试为什么会这样。如果依赖函数与调用它的函数来自同一模块,我将无法模拟它。但是如果将模拟函数移动到与调用它的函数的模块不同的单独模块,我能够克服这个问题。

不工作场景
模块 A (filename.ts)

export const callingFunction = () => {
  //....statements
  dependentFunction();
}

export const dependantFunction = () => {
  //....statements
  //resolve with something
}

filename.test.ts

import { callingFunction } from './fileName'

jest.mock('./fileName',() =>  ({
 ...jest.requireActuals('./fileName'),
 dependentFunction: jest.fn().mockImplementation(/*....Mocked implementation*/)
})

test('...test case description...', () => {
  const callingFunctionRespose: any = callingFunction();
  expect(callingFunctionResponse).toEqual(/*....something.....*/);
});

上面的 mock 没有覆盖 fileName.ts 模块导出的 dependentFunction。相反,当调用导出函数 callingFunction() 时,它使用模块中定义的实现。 (通过记录函数定义发现了这一点。

但是当依赖函数移动到它自己的单独模块时,不会观察到这种行为。

工作场景
fileName.ts

import { dependentFunction } from './dependentFunctions'

export const callingFunction = () => {
  //....statements
  dependentFunction();
}

dependentFunctions.ts

export const dependantFunction = () => {
  //....statements
  //resolve with something
}

fileName.test.ts

import { callingFunction } from './fileName'

jest.mock('./dependentFunctions',() =>  ({
 ...jest.requireActuals('./dependentFunctions'),
 dependentFunction: jest.fn().mockImplementation(/*....Mocked implementation*/)
})

test('...test case description...', () => {
  const callingFunctionRespose: any = callingFunction();
  expect(callingFunctionResponse).toEqual(/*....something.....*/);
});

您可以将函数作为模块导入

import * as module from './fileName'

模拟你可以做的实现

jest.spyOn(module, 'dependentFunction').mockImplementation(/*....Mocked implementation*/)

要调用其他函数,请使用 module.callingFunction()

抱歉更新晚了。但以下文章中的解决方案是修复:

https://medium.com/welldone-software/jest-how-to-mock-a-function-call-inside-a-module-21c05c57a39f