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

时间:2016-07-06 09:33:28

标签: javascript unit-testing typescript sinon sinon-chai

我需要断言是否使用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);
    }
}

2 个答案:

答案 0 :(得分:0)

//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();
    });
  });
});

答案 1 :(得分:0)

给出以下代码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);