Sinon js AssertError: expected stub to be called once but was called 0 times

Sinon js AssertError: expected stub to be called once but was called 0 times

我一直在学习 Sinon JS 进行单元测试,我正在努力让这个示例代码正常工作。我创建了一个简单的 "external" 库:

class MyLib {

   simpleMethod () {
      return 'some response';
   }

   static handler() {
      const myLib = new MyLib();
      myLib.simpleMethod();
   }
}

module.exports = MyLib;

然后,我有一个简单的测试套件:

const chai = require('chai');
const sinon = require('sinon');
const MyLib = require('./my-lib');

describe ('sinon example tests', () => {

  it ('should call simpleMethod once', () => {
     let stubInstance = sinon.stub(MyLib, 'simpleMethod');

     MyLib.handler();

     sinon.assert.calledOnce(stubInstance);
  });

});

但是我返回错误 "AssertError: expected stub to be called once but was called 0 times"。我知道这可能很明显,但为什么 simpleMethod 没有被调用?

simpleMethod 是一个实例方法。要存根实例方法,您应该存根原型。

在您的代码中试试这个。

myStub = sinon.stub(MyLib.prototype, 'simpleMethod');

记得在测试结束时恢复存根。

myStub.restore();