3

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

2 回答 2

1

给定以下代码 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);     
于 2018-03-08T19:37:02.670 回答
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();
    });
  });
});
于 2016-07-07T19:35:27.660 回答