Jasmine test for AngularJS nested callback, angularjsnested
Today I wrote a function that involves two callback functions. The approximate form is
function callbackFunction() {ServiceA.callbackA(data1, function(result1){//success function callbackServiceA.callbackA(data2, function(result2{return [result1, result2];}, function(error){console.log(error);});}, function(error){console.log(error);};}
I encountered a problem when writing jasmine unit test for this function. At first I wrote this:
First mock A ServiceA and callbackA
mockServiceA = jasmine.createSpyOn('ServiceA', ['callbackA']);
Then, use callFake to assume the callback result.
var data1 = 'data1';var data2 = 'data2';mockServiceA.callbackA.and.callFake(data1, function(){success(data1);}, function(){});mockServiceA.callbackA.and.callFake(data2, function(){success(data2);}, function(){});
The final result returned after this write is ['data2 ', 'data2'], because the second callFake will overwrite the first
Solution: define a result hash to specify the returned result according to parameter.
var data1 = 'data1';var data2 = 'data2';var result = {data1: data1,data2: data2}mockServiceA.callbackA.and.callFake(data, function(){success(result.data);}, function(){});
In this way, the mock result ['data1', 'data2 '] will be returned successfully.