I'm testing a function with this code:
return new Promise((ok, fail) => {
this.repository.findById(id, (error, result) => {
if (error)
return fail(error);
ok(result);
});
});
I want to test the path of the fail, i.e., when the findById method calls the callback with an error. I'm using sinon to generate a stub for my repository and its findById method, but I don't know how to force the stub to call the callback with the desired parameters
Anybody did something like that before?
Thanks
With Sinon 2, you can use the callsFake method of a stub:
sinon.stub(repository, 'findById').callsFake((id, callback) =>
callback(new Error('oops'))
);
See Sinon 2 documentation: http://sinonjs.org/releases/v2.1.0/stubs/
A more generic answer here: Every time I have to stub a callback, I do it like this
const stubFindId = sinon.stub(repository, 'findById');
stubGetitem.callsFake((value: string, callback: any) => {
return callback(true, false);
});