Monday, May 20, 2024
11
rated 0 times [  16] [ 5]  / answers: 1 / hits: 59261  / 9 Years ago, wed, april 22, 2015, 12:00:00

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/


More From » unit-testing

 Answers
11

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.


[#66953] Tuesday, April 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;