Tuesday, 15 July 2014

angularjs - Mocha/angular unit test never runs 'then' function -



angularjs - Mocha/angular unit test never runs 'then' function -

i'm trying test angular service returns promise in mocha chai, calling 'then' in unit test times out. service depends on sec service async $resource request. myservice.getdata() should internally info said asynchronous service , pass on promise controller, calls 'then' function on response. works great in controller, , absolutely fails in unit test.

service code:

// use: myservice.getdata.then(...) works beautifully in angular controllers getdata = function(dataid) { var datapromise; // students api, if necessary, or service if retrieved // datalist private property of service if(!datalist) { datapromise = asyncserviceusedbymyservice.asyncmethod({...}).$promise .then( function(response){ datalist = response; dosomedatamanipulation(); homecoming datalist; }, function(err) { homecoming err; } ); } // utilize existing studentlist if available else { datapromise = $q.when(function(){ homecoming datalist }); } homecoming datapromise; };

test code

describe('service test', function() { var expect = chai.expect, myservice, asyncserviceusedbymyservice; beforeeach(function() { var data, asyncservicemock; info =[...]; // mock async dependency asyncservicemock = { asynchmethod: function () { var deferred = q.defer(); deferred.resolve(data); homecoming {$promise: deferred.promise}; } }; module('myapp'); module(function($provide){ $provide.value('asyncserviceusedbymyservice', asyncservicemock); }); inject(function(myservice, $q, asyncserviceusedbymyservice) { myservice = myservice; q = $q; courseenrollmentservice = courseenrollmentservicemock; }); }); // passes it('should available', function() { expect(!!myservice).to.equal(true); }); // 'then' function never called, unit test times out it('should items async dependency', function(done) { myservice.getdata().then(function(response) { expect(response).to.have.property('length').that.equals(5); done(); }); }); });

how 'then' function of myservice run in unit test, mocked info (which should near instantaneous, since we're not making actual api call?).

note: i've tried 'chai-as-promised' syntax, next seems time out

it('should items async dependency', function(done) { expect(myservice.getdata()).to.eventually.have.property('length').that.equals(5).and.notify(done); });

the promises resolution in angular made in digest cycle, can trigger cycle calling scope.$apply(); in test.

you can read more here.

angularjs unit-testing asynchronous mocha karma-runner

No comments:

Post a Comment