Home Ask Login Register

Developers Planet

Your answer is one click away!

Healforgreen February 2016

Unit testing a function's parameter that is a function

I would like to know how to write a unit test for a parameter that is a function in JavaScript.

For example,

_.forEach($scope.all, function(key, value) {

I am able to enter the forEach function in my unit test, and am also able to access the first parameter, but I am not able to access the function(key, value) {} param.

Secondly, what is that function parameter called? Is it just an anonymous function?


Jacob February 2016

In your unit tests, you shouldn't be concerned about testing every implementation detail. You don't really care about that anonymous function, but rather that the side effects or return value of your SUT matches expectations. You should test that $scope.arr contains the expected data after calling your function.

If you really needed to get access to that function, you'd have to use something like a spy to record when _.forEach is called, then access that argument:

var forEachSpy = sinon.spy(_, 'forEach');
var forEachFn = forEachSpy.lastCall.args[1];

But again, I would argue that testing in this manner does not add value and only leads to brittle tests that do not remain useful upon refactoring of implementation details. For example, say you use a regular Array forEach in the future; your test would break, but you don't really care how you loop through the structure, only that your scope is correct.

Post Status

Asked in February 2016
Viewed 3,260 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life