如何验证构造函数是否是使用 sinon 调用的

How to verify that a constructor was called using sinon

本文关键字:sinon 调用 是否是 构造函数 何验证 验证      更新时间:2023-09-26

我需要断言构造函数是否是使用 sinon 调用的。以下是我创建间谍的方法。

let nodeStub: any;
nodeStub = this.createStubInstance("node");

但是,如何验证是否使用相关参数调用了此构造函数?下面是构造函数的实际调用方式。

 node = new node("test",2);

任何帮助将不胜感激。

下面是我的代码。

import {Node} from 'node-sdk-js-browser';
export class MessageBroker {
    private node: Node;
    constructor(url: string, connectionParams: IConnectionParams) {
        this.node = new Node(url, this.mqttOptions, this.messageReceivedCallBack);
    }
}

给定以下代码myClient.js:

const Foo = require('Foo');
module.exports = {
   doIt: () => {
      const f = new Foo("bar");
      f.doSomething();
  }
}

你可以编写这样的测试:

const sandbox = sinon.sandbox.create();
const fooStub = {
   doSomething: sandbox.spy(),
}
const constructorStub = sandbox.stub().returns(fooStub);
const FooInitializer = sandbox.stub({}, 'constructor').callsFake(constructorStub);
// I use proxyquire to mock dependencies. Substitute in whatever you use here.
const client2 = proxyquire('./myClient', {
    'Foo': FooInitializer,
});
client2.doIt();
assert(constructorStub.calledWith("bar"));
assert(fooStub.doSomething.called);     
//module.js
var Node = require('node-sdk-js-browser').Node;
function MessageBroker(url) {
  this.node = new Node(url, 'foo', 'bar');
}
module.exports.MessageBroker = MessageBroker;
//module.test.js
var sinon = require('sinon');
var rewire = require('rewire');
var myModule = require('./module');
var MessageBroker = myModule.MessageBroker;
require('should');
require('should-sinon');
describe('module.test', function () {
  describe('MessageBroker', function () {
    it('constructor', function () {
      var spy = sinon.spy();
      var nodeSdkMock = {
        Node: spy
      };
      var revert = myModule.__set__('node-sdk-js-browser', nodeSdkMock);
      new MessageBroker('url');
      spy.should.be.calledWith('url', 'foo', 'bar');
      revert();
    });
  });
});