Jorayen
Jorayen

Reputation: 1971

Sinon.js stub an anonymous function inside an object

So I'm unit-testing my code and I face a problem with testing an anonymous function being called inside the function that I'm unit-testing. The reason for why I didn't make the anonymous function an instance named function, is because I need the closure of some of the variables from the unit-tested function to be used inside the anonymous function. Example to illustrate:

function funcBeingTested(done, arg1) {
    var self = this; 
    ...
    self.array.push({
        "arguments": [
            "x", "y", function (error, result) {
                // do some stuff with arg1...
                done(error, arg1);
            }, "z"
        ]
    });
    ...
    self.run(); // Eventually will call the anonymous function above from 'self.array'
}

Now, my question is there a way to test what's going on inside that anonymous function using sinon.js ?
Someway I could call it with specific arguments as part of the unit test of funcBeingTested() ?

Edit: To clear up any misconception about what I'm trying to achieve, I wish to be able to unit test the anonymous function it-self and cover all it's possible branches to get 100% coverage. I already know how to check if the done() callback was called, and with what args using sinon.js, the problem is how would I test the anonymous function in an isolation, and call it with specific arguments to cover all possible branches.

Upvotes: 2

Views: 3233

Answers (1)

gnerkus
gnerkus

Reputation: 12047

You can test the anonymous function by defining the done function and spying on it. You need to know if this function is called with the right arguments when the anonymous function is called.

For example:

// Define the `done` function.
var doneFunction = function (error, args) {
  // do something
};

// Spy on the `done` function to register calls.
var doneSpy = sinon.spy(doneFunction);

// Test the funcBeingTested
funcBeingTested(doneFunction, someArg);

// Check that doneFunction was called
assert(doneSpy.calledWith(someArg));

You can read more about the Spy API for Sinon

Upvotes: 1

Related Questions