Jest spyOn不适用于ES6类方法



我创建了一个带有一些方法的类,我想模拟该类中的方法,所以我尝试使用spyOn((,但它不起作用?我在spyOn((中使用myClass.prototype而不是myClass,但它仍然不起作用。

class myClass {
constructor(){
}
_methodA () {
}
_methodB() {
}
main () {
const res1 = _methodA();
const res2 = _methodB();

}
}

测试:

it('Testing' , () => {
// Some mock data passed below
jest.spyOn(myClass.prototype, '_methodA').mockReturnValue(mockData1)
jest.spyOn(myClass.prototype, '_methodB').mockReturnValue(mockData2)
const obj = new myClass();
obj.main();
expect(myClass._methodA).toHaveBeenCalledTimes(1);
expect(myClass._methodB).toHaveBeenCalledTimes(1);
});

您可以监视类实例方法:

it("Testing", () => {
// Some mock data passed below
const obj = new myClass();
const spyA = jest.spyOn(obj, "_methodA").mockReturnValue({});
const spyB = jest.spyOn(obj, "_methodB").mockReturnValue({});
obj.main();
expect(spyA).toHaveBeenCalledTimes(1);
expect(spyB).toHaveBeenCalledTimes(1);
});

您可以监视方法:

it("Testing", () => {
// Some mock data passed below
const spyA = jest.spyOn(myClass.prototype, "_methodA").mockReturnValue({});
const spyB = jest.spyOn(myClass.prototype, "_methodB").mockReturnValue({});
const obj = new myClass(); 
obj.main();
expect(spyA).toHaveBeenCalledTimes(1);
expect(spyB).toHaveBeenCalledTimes(1);
});

使用Db数据的另一种情况也是可能的:

it("Testing", () => {
const obj = new classA();
obj.main();
const spyA = jest.spyOn(DBClass.prototype, "getData").mockReturnValue({}); // DBClass could be a db class or a mock class
expect(spyA).toHaveBeenCalledTimes(1);
});

最新更新