Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon: force callback call

Tags:

node.js

sinon

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

like image 406
Jose Selesan Avatar asked Apr 28 '17 12:04

Jose Selesan


People also ask

How do you stub callback functions?

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.

What is callsFake in Sinon?

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.

What does Sinon spy do?

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.

What does sandbox stub do?

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.


1 Answers

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/

like image 81
Patrick Hund Avatar answered Oct 21 '22 20:10

Patrick Hund