更新:我在https://github.com/magicmark/jest-how-do-i-mock-x/blob/master/src/function-in-same-module/README中收集了此方法和其他方法。 md
正确模拟以下示例的最佳方法是什么?
问题在于,导入时间过后,foo
将原始引用保持不变bar
。
module.js:
export function bar () {
return 'bar';
}
export function foo () {
return `I am foo. bar is ${bar()}`;
}
module.test.js:
import * as module from '../src/module';
describe('module', () => {
let barSpy;
beforeEach(() => {
barSpy = jest.spyOn(
module,
'bar'
).mockImplementation(jest.fn());
});
afterEach(() => {
barSpy.mockRestore();
});
it('foo', () => {
console.log(jest.isMockFunction(module.bar)); // outputs true
module.bar.mockReturnValue('fake bar');
console.log(module.bar()); // outputs 'fake bar';
expect(module.foo()).toEqual('I am foo. bar is fake bar');
/**
* does not work! we get the following:
*
* Expected value to equal:
* "I am foo. bar is fake bar"
* Received:
* "I am foo. bar is bar"
*/
});
});
谢谢!
编辑:我可以更改:
export function foo () {
return `I am foo. bar is ${bar()}`;
}
至
export function foo () {
return `I am foo. bar is ${exports.bar()}`;
}
但这是p。我认为到处都是丑陋的:/
更新:我在https://github.com/magicmark/jest-how-do-i-mock-x/blob/master/src/function-in-same-module/README中收集了此方法和其他方法。 md
jest
GH页面上查看此问题线程github.com/facebook/jest/issues/936#issuecomment-545080082