Jest间谍On不适用于ES6类方法?

roc*_*one 1 javascript jestjs

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

class myClass {

    constructor(){

    }

    _methodA () {

    }

    _methodB() {

    }

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

}
Run Code Online (Sandbox Code Playgroud)

测试:

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

});
Run Code Online (Sandbox Code Playgroud)

lis*_*tdm 5

您可以监视类实例方法:

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);
});
Run Code Online (Sandbox Code Playgroud)

您可以监视方法:

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);
});
Run Code Online (Sandbox Code Playgroud)

使用 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);
});
Run Code Online (Sandbox Code Playgroud)