Reputation: 675
I'm not sure what is the best way to do unit test for function foo, since the callback is passed to function bar, the unit test for foo I wrote is also testing the function bar.
Is there any way I could only test the logic inside the foo? In below use case, I just want to make sure foo function can increase value by 1 then pass everything to bar. How bar handle the value should be tested in bar unit test not foo unit test.
function bar(value, callback) {
value = value + 1;
callback(value);
}
function foo(value, callback) {
value = value + 1;
bar(value, callback);
}
//test for function bar
it('should be able to increase value by 1', function (done) {
bar(1, function (value) {
expect(value).to.equal(2);
done();
});
});
//test for function foo
it('should be able to increase value by 2', function (done) {
foo(1, function (value) {
expect(value).to.equal(3);
done();
});
});
Upvotes: 0
Views: 768
Reputation: 17505
This code is more or less analogous to the following synchronous code:
function bar(value) {
value = value + 1;
return value;
}
function foo(value) {
value = value + 1;
return bar(value);
}
Now that we're looking at something a little more familiar, we can ask your question again. The answer, clearly, is no - foo
always calls bar
.
If you can test both foo
and bar
, it shouldn't matter - based on which of those fail, you can figure out where the error is.
If bar
is something like a db call, which you might not be able to test, you should look into the idea of "mocking" functions/objects. If bar
isn't something that should be mocked, but foo
should be tested without using bar
, then this indicates that bar
should probably be passed as an argument to foo
, rather than hardcoded in to that function.
Upvotes: 1