Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying function call and inspecting arguments using sinon spies

I would like to verify that bar() is called inside foo() from my unit test.

I figured that Sinon spies might be suitable, but I don't know how to use them.

Is there any way to check that the method is called? Perhaps even extracting the arguments used in the bar() call?

var spy = sinon.spy(foo);  function foo(){     bar(1,2,3); }  function bar(){ }  foo();  // what to do with the spy? 

http://jsfiddle.net/8by9jg07/

like image 670
filur Avatar asked Apr 22 '15 14:04

filur


People also ask

How do you spy a function in Sinon?

var spy = sinon. spy(); Creates an anonymous function that records arguments, this value, exceptions and return values for all calls.

What is Sinon in testing?

Sinon JS is a popular JavaScript library that lets you replace complicated parts of your code that are hard to test for “placeholders,” so you can keep your unit tests fast and deterministic, as they should be.

How does Sinon stub work?

Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished? require('request') will return the same (object) reference, that was created inside the "request" module, every time it's called.

What is Sinon mock?

What are mocks? Mocks (and mock expectations) are fake methods (like spies) with pre-programmed behavior (like stubs) as well as pre-programmed expectations. A mock will fail your test if it is not used as expected.


1 Answers

In your case, you are trying to see if bar was called, so you want to spy bar rather than foo.

As described in the doc :

function bar(x,y) {   console.debug(x, y); } function foo(z) {   bar(z, z+1); } // Spy on the function "bar" of the global object. var spy = sinon.spy(window, "bar");  // Now, the "bar" function has been replaced by a "Spy" object // (so this is not necessarily what you want to do)   foo(1);  bar.getCall(0).args => should be [1,2] 

Now, spying on the internals of the function strongly couples your test of "foo" to its implementation, so you'll fall into the usual "mockist vs classical" debate.

like image 175
phtrivier Avatar answered Sep 26 '22 00:09

phtrivier