正确模仿以下示例的最佳方法是什么?
问题是,在导入时间之后,foo
将保留对原始非模拟 bar
的引用。
返回文章页面
export function bar () {
return 'bar';
}
export function foo () {
return `I am foo. bar is ${bar()}`;
}
返回文章页面
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()}`;
}
但在我看来,到处都这样做是相当丑陋的。