正確模擬以下示例的最佳方法是什麼?如何在使用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