Jest spy在测试函数中的函数时不工作



我试图在基于类的实体中测试一个函数,并试图监视正在测试的实体中调用的另一个函数。但是,即使子函数被调用了一次,Jest也没有发现它,并说它被调用了0次。

假设这是我的课:

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);
});
});

我在这里错过了什么?

您首先调用函数,然后监视另一个函数。在函数调用前尝试间谍活动

describe('ExampleComponent', () => {
beforeEach(() => {
client = new Example();
});
it('should call function2 once', async() => {

const function2Spy = jest.spyOn(client, 'function2'); 
client.function1();

expect(function2Spy).toHaveBeenCalledTimes(1);
});
});

最新更新