【问题标题】:Unable to mock a dependent function if its from the same module如果来自同一模块,则无法模拟依赖函数
【发布时间】:2022-02-26 11:38:12
【问题描述】:

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

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

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

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

文件名.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
}

文件名.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.....*/);
});

【问题讨论】:

标签: javascript typescript unit-testing jestjs


【解决方案1】:

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

import * as module from './fileName'

要模拟你可以做的实现

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

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

【讨论】:

    【解决方案2】:

    对于迟到的更新表示歉意。但以下文章中的解决方案是修复:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多