【问题标题】:NodeJS: How check if a class/stub is called with new?NodeJS:如何检查一个类/存根是否被 new 调用?
【发布时间】:2019-09-02 11:48:26
【问题描述】:

我有以下代码,用于启动设备命令类。

class DeviceCommand {

  /**
   * DeviceCommand constructor.
   *
   * @param  {String} cmd - The command to send.
   * @param  {String} ack - The acknowledgement from the device.
   */
  constructor(cmd, ack) {

    if (arguments.length !== 2) {
      throw new Error('Expected at least 2 paramters');
    }

    this.cmd = cmd;
    this.ack = ack;
  }

}

我想测试这个类是否被 new 调用,使用下面的

const ClassStub = sandbox.spy(() => sinon.createStubInstance(DeviceCommand));
ClassStub.should.have.been.calledWithNew;

但是,这实际上并没有执行测试,因为以下也通过了

ClassStub.should.not.have.been.calledWithNew;

虽然,以下失败

sinon.assert.calledWithNew(ClassStub);

不应该那样做吗?谢谢。

【问题讨论】:

    标签: node.js mocha.js sinon chai


    【解决方案1】:

    要检查是否使用new 调用了构造函数,需要将构造函数包装在间谍中,然后验证是否使用new 调用了间谍。

    这是一个简单的例子:

    lib.js

    class DeviceCommand { }
    
    module.exports = {
      DeviceCommand
    };
    

    lib.test.js

    const lib = require('../src/lib');
    const sinon = require('sinon');
    
    it('should verify that DeviceCommand was called with new', () => {
      const spy = sinon.spy(lib, 'DeviceCommand');
      const instance = new lib.DeviceCommand();
      sinon.assert.calledWithNew(spy);  // Success!
    })
    

    【讨论】:

    • 在您的解决方案中,以下 const instance = new lib.DeviceCommand(); 实际上使用 New 调用存根。那么这个测试有用吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2014-09-29
    相关资源
    最近更新 更多