2016-07-06 113 views
0

我需要斷言是否使用sinon調用構造函數。以下是我如何創建一個間諜。如何驗證構造函數是使用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); 
    } 
} 

回答

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

嘿夥計,我的類需要測試是稱爲MessageBroker。它具有此導入行,「從node-sdk-js-browser';」導入{Node}。這裏Node是一個命名的導入。它來自模塊node-sdk-js-browser。 Node構造函數是我需要窺探並驗證它是否被調用的。你能編輯這個例子來適應這個嗎?因爲我是Javascript的新手,它很容易讓人困惑:( – mayooran

+0

它應該爲你提供一般的想法,如果你提供了我的代碼(甚至簡化了),我可以更新我的示例 –

+0

我已經用我的代碼編輯器編輯了這個問題,當我調用MessageBroker構造函數時,我需要驗證Node構造函數是否被調用。如果你可以幫助我一個這樣的例子: – mayooran

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);