I have the following constructor which takes a few parameters.
constructor(url: string, mqttOptions: MqttOptions, messageReceivedCallBack: IMessageReceivedCallBack) {
if (!_.isString(url) || _.isEmpty(mqttOptions || _.isEmpty(messageReceivedCallBack))) {
throw new MyNodeError('invalid url value');
} else {
this.createConnection(url,mqttOptions);
}
}
How can I create a spy instance using sinon in order to verify that an exception is thrown when one of the parameters is empty? I saw this question Mocking JavaScript constructor with Sinon.JS but its a constructor with no parameters. Any help would be much appreciated.
I don't see why you need to create a spy for that? You should be able to just test it like so:
it('should throw if one of the parameters is empty', function() {
expect(constructor.bind(null, null, mqttOptions, messageReceivedCallback)).to.throw(MyNodeError);
}
In the example url
parameter is set to null
and I'm assuming the variables mqttOptions
and messageReceivedCallback
to be defined (not shown).
This, for example, mirrors what you're looking for (if I understood the question correctly) and works as expected for me:
it.only('', function() {
function C(a) { if (!a) throw new TypeError('a was empty'); }
expect(C.bind(null, 'b')).to.not.throw(TypeError);
expect(C.bind(null, null)).to.throw(TypeError);
})
Try whether the following approach works for you!
import {assert} from 'chai';
import MyNodeError from './path/to/MyNodeError'
import ClassToTest from './path/to/Class';
describe('MyClass', function() {
function test() {
new ClassToTest('', {}, null);
}
it("Should throw exception when invalid parameters passed", function(){
assert.throw(test, MyNodeError, "invalid url value");
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.