I've been looking at this for hours. I've tried example after example. I just can't seem to get this to work. Please help =)
I am doing all this on a clean clone of the angular-seed repo (git://github.com/angular/angular-seed.git). I have made no changes except those listed below.
Problem:
When I run the following, the test works. Note that in this version, the service returns a value before doing any kind of $http call.
./app/js/services/services.js
'use strict';
angular.module('myApp.services', [])
.factory("exampleService", function ($http) {
return {value:"goodValue"};
$http.get("/exampleUrl")
.success(function () {
return {value:"goodValue"};
})
.error(function () {
return {value:"badValue"};
})
});
./test/unit/servicesSpec.js
'use strict';
describe('service', function() {
var $httpBackend;
beforeEach(module('myApp.services'));
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get("$httpBackend");
$httpBackend.when("GET", "/exampleUrl")
.respond({value:"goodValue"});
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('exampleService', function () {
it('.value should be "goodValue"', inject(function (exampleService) {
expect(exampleService.value).toEqual("goodValue");
}));
});
});
Results
info (watcher): Changed file "/home/username/mocktest/test/unit/servicesSpec.js".
Chrome 26.0: Executed 5 of 5 SUCCESS (0.136 secs / 0.035 secs)
When I remove the line return {value:"goodValue"};
and actually let it run the $http.get()
, the whole thing breaks with the following errors:
info (watcher): Changed file "/home/username/mocktest/app/js/services.js".
Chrome 26.0 service exampleService .value should be "goodValue" FAILED
TypeError: Cannot read property 'value' of undefined
at null.<anonymous> (/home/username/mocktest/test/unit/servicesSpec.js:22:28)
at Object.invoke (/home/username/mocktest/app/lib/angular/angular.js:2864:28)
at workFn (/home/username/mocktest/test/lib/angular/angular-mocks.js:1758:20)
Error: Declaration Location
at window.jasmine.window.inject.angular.mock.inject (/home/username/mocktest/test/lib/angular/angular-mocks.js:1744:25)
at null.<anonymous> (/home/username/mocktest/test/unit/servicesSpec.js:21:40)
at null.<anonymous> (/home/username/mocktest/test/unit/servicesSpec.js:20:3)
at /home/username/mocktest/test/unit/servicesSpec.js:4:1
Error: Unflushed requests: 1
at Error (<anonymous>)
at Function.$httpBackend.verifyNoOutstandingRequest (/home/username/mocktest/test/lib/angular/angular-mocks.js:1225:13)
at null.<anonymous> (/home/username/mocktest/test/unit/servicesSpec.js:17:18)
Chrome 26.0: Executed 5 of 5 (1 FAILED) (0.14 secs / 0.043 secs)
Thoughts
I suspect I need to do some kind of returning of a promise object in the service, then resolve it afterwards, but I have no idea what that would be. Any help appreciated.