I need to assert whether a constructor was called using sinon. Below is how I can create a spy.
let nodeStub: any;
nodeStub = this.createStubInstance("node");
But how can I verify that this constructor was called with the relevant parameters? Below is how the constructor is actually called.
node = new node("test",2);
Any help would be much appreciated.
Below is the code I have.
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);
}
}
Given the following code myClient.js:
const Foo = require('Foo');
module.exports = {
doIt: () => {
const f = new Foo("bar");
f.doSomething();
}
}
You can write a test like this:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With