【发布时间】: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