Today wrote a function, which involved two callback, the approximate form of
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);};}
A problem was encountered while writing Jasmine unit test for this function. At first I wrote this:
First mock a servicea and Callbacka
Mockservicea = Jasmine.createspyon (' ServiceA ', [' Callbacka ']);
And then through Callfake hypothesis callback results
var data1 = ' data1 '; var data2 = ' data2 '; MockServiceA.callbackA.and.callFake (data1, function () {success (data1);}, function () {}); MockServiceA.callbackA.and.callFake (data2, function () {success (DATA2);}, function () {});
But the result of this write is [' data2 ', ' data2 '], because the second callfake will overwrite the first time
Workaround, define a result hash to specify the return result based on 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 result of the mock will be returned successfully [' Data1 ', ' data2 ']
Jasmine test for AngularJS nested callback