正确模拟以下示例的最佳方法是什么?如何在使用jest的同一模块中模拟函数
问题是,在导入时间后,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。在我看来丑陋无处不在:/
我通常不喜欢依赖注入的粉丝,因为您允许测试来改变代码的写法。这就是说,这比当前更高级的答案要好得多,这个答案很丑陋 – Sean