使用 Sinon 调用方法的测试构造函数

Test constructor calling a method with Sinon

我想确保构造函数在用 Sinon 实例化时调用方法,但是,我似乎无法让它工作,因为我相信 sinon 没有观察正确的实例化:

class Test {
  constructor() {
    this.someFunction();
  }

  someFunction() {
    return 1;
  }
}

...和测试

describe('constructor', () => {

  it('should call someFunction()', () => {
    const spyFunc = new Spy(new Test(), 'someFunction');
    expect(spyFunc.calledOnce).to.be.true;
  });

});

在调用构造函数之前尝试监视 Test.prototype.someFunction。 像这样

sinon.spy(Test.prototype, 'someFunction')
const spyFunc = new Test();
expect(spyFunc.someFunction.calledOnce).to.be.true;