I'm writing my first unit test to check the functionality of a AngularJS service. This is the part of the service with the getList function I'm testing:
(function() {
'use strict';
angular
.module('app.services')
.factory('RestService', RestService);
RestService.$inject = [ '$http' ];
function RestService($http) {
var service = {
getList: getList,
...
};
return service;
function getList(url) {
return $http.get(url)
.then(function(response) {
console.log('RestService: got list: ' + response.data.length);
return response.data;
})
.catch(function(errResponse) {
console.error('RestService: error getting list: ' + errResponse.status);
});
}
And I've written the following unit test:
'use strict';
describe('Test Rest Service', function() {
var httpBackend;
var RestService;
var reqHandler;
beforeEach(module('app.services'));
beforeEach(inject(function ($httpBackend, _RestService_) {
httpBackend = $httpBackend;
RestService = _RestService_;
reqHandler = httpBackend.when('GET', '/api/events')
.respond(200, '[{ "event": 1 }, { "event": 2 }]');
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should get a list of events', function() {
var url = '/api/events';
httpBackend.expectGET(url);
RestService.getList(url).then(function(response) {
httpBackend.flush();
expect(response.length).toEqual(2);
});
});
});
When I run the test I get the following error:
Test Rest Service
PhantomJS 1.9.8 (Windows 8 0.0.0) Test Rest Service "after each" hook FAILED
Error: Unflushed requests: 1
My first guess is that then then part of the test is not executing but I can't find a way to check this. Can anyone explain why I have an unflushed request? Also, is there some way I can step through the test or at least print the variables to screen so I can figure out what's going on?
Thanks in advance!
httpBackend.flush is function, which causes return data from httpBackend. You can not call it in then block, because then is called when data are received (in this case never).
Right test code is
it('should get a list of events', function() {
var url = '/api/events';
httpBackend.expectGET(url);
RestService.getList(url).then(function(response) {
expect(response.length).toEqual(2);
});
httpBackend.flush();
});
working example - http://plnkr.co/edit/TA1HdQJaZHuShJiIIw6V?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With