JEST:如何存根在类的构造函数中调用的方法

PJ1*_*405 4 unit-testing jestjs babeljs angular

示例如下所示:

export class ABC {
  constructor() {
    this.method1();
  }

  method1() {
    console.log();
  }
}
Run Code Online (Sandbox Code Playgroud)

假设有一些对外部方法的调用method1正在停止代码继续前进。我不想进去method1

现在的问题是当我这样做时:

describe('test cases!', () => {
  let abc: ABC;
  beforeEach(() => {
    spyOn(abc, 'method1').and.stub();
    abc = new ABC();
    jest.resetAllMocks();
  });
});
Run Code Online (Sandbox Code Playgroud)

这是抛出错误。

类初始化后我无法将spyOn. 大家有什么想法吗?

感谢帮助。

Bri*_*ams 6

method1存在于ABC.prototype,您可以监视它并在构建 的新实例之前替换实现ABC

class ABC {
  constructor() {
    this.method1();
  }
  method1() {
    throw new Error('should not get here');
  }
}

test('ABC', () => {
  const spy = jest.spyOn(ABC.prototype, 'method1');  // spy on the method of the prototype
  spy.mockImplementation(() => {});  // replace the implementation
  const abc = new ABC();  // no error
  expect(spy).toHaveBeenCalled();  // SUCCESS
})
Run Code Online (Sandbox Code Playgroud)