問題描述
tl;博士:
- 我用茉莉花;
- 我想測試調用
bbb
的aaa
函數模塊; - 我想監視
bbb
,但最終aaa
調用了原bbb
函數,不是spy;
- I use Jasmine;
- I want to test
aaa
function which calledbbb
from the same module; - I want to spy on
bbb
, but eventuallyaaa
called the originalbbb
function, not a spy;
如何強制 aaa
調用間諜?
How can I force aaa
to call the spy?
模塊:
export function aaa() {
return bbb();
}
export function bbb() {
return 222;
}
測試:
import * as util from 'my-module';
describe('aaa test', () => {
let bbbSpy: Spy;
beforeEach(() => {
bbbSpy = spyOn(util, 'bbb');
});
it('should return SPYED', () => {
bbbSpy.and.returnValue('SPYED!!');
const result = util.aaa();
expect(result).toEqual('SPYED!!'); // Doesn't work - still 222
});
});
所以,這基本上是行不通的.誰能幫幫我?
So, basically that doesn't work. Can anyone help me please?
P.S.我不想更改模塊的代碼,因為在這種情況下我將不得不更改項目中的大量代碼.我需要一個通用的測試解決方案.
P.S. I don't want to change the module's code, because in that case I'll have to change tons of code in the project. I need a general solution for tests.
推薦答案
即使認為不是同一個框架,有一個相關的問題告訴你為什么這不起作用:如何使用 jest 在同一模塊中模擬函數.基本上,您將無法訪問該函數的固定引用,而是明確表示該函數與模塊上下文中的函數相同.
Even thought is not the same framework, there is a related question that gives you why this doesnt work: How to mock functions in the same module using jest. Basically you wont be able to access this fixed reference of the function and instead make clear that is the same function as in the context of the module.
我知道這不滿足您在問題中發布的約束,但很明顯,您想要實現的目標是無法通過使用 spy.
I know this doesn't satisfy the constraint that you post in your question, but it just makes obvious that what you want to achieve is not possible by using spy.
使用 JavaScript,沒有辦法交換對某些東西的引用.您不能換出模塊內部的函數.當您嘗試在示例中使用 spyOn.and.returnValue 覆蓋 bbb 時,您只是在修改測試中的本地綁定 bbb,但它對您其他文件中的 bbb 綁定沒有影響.
With JavaScript, there is no way to swap out references to something. You cannot swap out a function that is internal to a module. When you try to overwrite bbb with spyOn.and.returnValue in your example, you are just modifying the local binding bbb in your test but it has no effect on the bbb binding in your other file.
這篇關于SpyOn 單獨導出的 ES6 函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!