angularjs - Angular Unit Testing Service with multiple service calls using $q.all -
ok here scenario trying unit test jasmine. have service defined similar service below:
(function () { 'use strict'; angular.module('mymodule') .service('myservice', myservice); myservice.$inject = ['$q', '$resource', 'progressservice', 'myservice2', 'myservice3', 'ngdialog']; function myservice($q, $resource, progressservice, myservice2, myservice3, ngdialog) { var self = this; self.datalistsvc2 = []; self.datalistsvc3 = []; self.datafromresource = null; self.myroutine = myroutine; var myresource = $resource('/someurl/webapi/getdata'); //trying test routine!!! function myroutine(param1, param2) { return progressservice.show($q.all([ myresource.get({ param1: param1 }).$promise.then(function (response) { self.datafromresource = response; }), myroutine2(param2), myroutine3(param2) ])); } function myroutine2(param) { return myservice2.getsomedata(param).then(function (response) { var results = []; self.datalistsvc2 = []; response.foreach(function (item) { item.addfield1 = null; item.addfield2 = false; results.push(item); }); self.datalistsvc2 = results; }); } function myroutine3(param) { return myservice3.getsomemoredata(param, [6]) .then(function (response) { self.datalistsvc3 = response; }); } } })();
i trying write unit test myservice.myroutine() , not having luck, suspect due $q.all array of promises. here test settled on not ideal , don't feel it's testing of value. have tried "mocking" 3 requests $httpbackend no luck 3 responses come in array undefined values. searched around , web , finding $q.all([]) unit tests referencing controllers not services. if has input appreciated. here settled time being:
describe('my service: ', function () { var $httpbackend; beforeeach(module('mymodule')); beforeeach(inject(function ($injector) { // set mock http service responses $httpbackend = $injector.get('$httpbackend'); })); it('can call myroutine myservice', inject(function (myservice) { //arrange var expectedval1 = 1234; var expectedval2 = 1234; spyon(myservice, "myroutine"); //act myservice.myroutine(expectedval1, expectedval2); //assert expect(myservice.myroutine).tohavebeencalled(); })); });
use $httpbackend.when('get', '/someurl/webapi/getdata').respond(data);
fake http requests. should fake myservice2.getsomedata
method , myservice3.getsomemoredata
guess methods create http request fake them in same manner.
expect(myservice.myroutine).tohavebeencalled();
is irrelevant called manually ;-).
var fixture = {/*some data ... */}; it('can call myroutine myservice', inject(function (myservice) { $httpbackend.when('get', '/someurl/webapi/getdata').respond(fixture); //act myservice.myroutine(expectedval1, expectedval2); $rootscope.$apply() //assert expect(myservice.datafromresource).tobe(fixture); }));
Comments
Post a Comment