I'm trying to test an angular service that returns a promise in mocha chai, but calling 'then' in a unit test times out. My service depends on a second service with an async $resource request. myService.getData() should internally get data from said asynchronous service and pass on the promise to the controller, which calls a 'then' function on the response. This works great in the controller, and absolutely fails in the unit test.
Service code:
// use: myService.getData.then(...) works beautifully in angular controllers
getData = function(dataId) {
var dataPromise;
// get students from the api, if necessary, or from the service if already retrieved
// dataList is a private property of the service
if(!dataList) {
dataPromise = asyncServiceUsedByMyService.asyncMethod({...}).$promise
.then(
function(response){
dataList = response;
doSomeDataManipulation();
return dataList;
},
function(err) {
return err;
}
);
}
// use the existing studentList if available
else {
dataPromise = $q.when(function(){
return dataList
});
}
return dataPromise;
};
Test Code
describe('Service Test', function() {
var expect = chai.expect,
myService,
asyncServiceUsedByMyService;
beforeEach(function() {
var data,
asyncServiceMock;
data =[...];
// mock the async dependency
asyncServiceMock = {
asynchMethod: function () {
var deferred = q.defer();
deferred.resolve(data);
return {$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 be available', function() {
expect(!!myService).to.equal(true);
});
// 'then' function is never called, unit test times out
it('should get all items from async dependency', function(done) {
myService.getData().then(function(response) {
expect(response).to.have.property('length').that.equals(5);
done();
});
});
});
How do I get the 'then' function of myService to run in the unit test, so it will get the mocked data (which should be near instantaneous, since we're not making an actual api call?).
Note: I've also tried 'chai-as-promised' syntax, but the following seems to time out
it('should get all items from async dependency', function(done) {
expect(myService.getData()).to.eventually.have.property('length').that.equals(5).and.notify(done);
});