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
Configuring Stub Behavior in Source CodeDefine the stub logic in the Stub Callback function, using the available input/output parameters. You can copy the Stub Callback signature from the stub file. See Stub Callback Execution. You can modify the name of the Stub Callback function, if needed.
In Sinon, a fake is a Function that records arguments, return value, the value of this and exception thrown (if any) for all of its calls. A fake is immutable: once created, the behavior will not change. Unlike sinon. spy and sinon. stub methods, the sinon.
Sinon spies are used to record information about function calls. Unlike mocks or stubs, spies do not replace the function being called. Spies just record what parameters the function was called with, what value it returned, and other information about the function execution.
sandbox.Causes all stubs and mocks created from the sandbox to return promises using a specific Promise library instead of the global one when using stub. rejects or stub. resolves . Returns the stub to allow chaining.
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/
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