[英]Jest spy not working while testing a function within a function
我正在嘗試在基於類的實體中測試 function 並嘗試監視在我正在測試的實體中被調用的另一個 function。 但是,即使子 function 被調用一次,Jest 也未能監視它並說它被調用了 0 次。
假設這是我的 class:
class Example {
function1() {
const data = this.function2();
return data;
}
function2() {
...some code
}
}
所以要測試function1
,我這樣做:
describe('ExampleComponent', () => {
beforeEach(() => {
client = new Example();
});
it('should call function2 once', async() => {
const callFunction1 = client.function1();
const function2Spy = jest.spyOn(client, 'function2');
expect(function2Spy).toHaveBeenCalledTimes(1);
});
});
我在這里想念什么?
您首先調用 function,然后監視另一個 function。 嘗試在 function 調用之前進行間諜活動
describe('ExampleComponent', () => {
beforeEach(() => {
client = new Example();
});
it('should call function2 once', async() => {
const function2Spy = jest.spyOn(client, 'function2');
client.function1();
expect(function2Spy).toHaveBeenCalledTimes(1);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.