Reputation: 10250
I'm having difficulty learning to unit test some AngularJS code using Karma and am getting hung up on the use of $httpBackend. I've created a distilled version of the test, showing only where I mock the get request and expect to see a non-failing call to httpBackend.get(...)
.
describe('Basics', function() {
var httpBackend;
beforeEach(angular.mock.inject(function($httpBackend) {
httpBackend = $httpBackend;
httpBackend.when("GET", "/foo.json").respond("{\"name\":\"value\"}");
}));
it('should complete this task', function() {
console.log(httpBackend);
var getFoo = httpBackend.get("/foo.json"); // line 11
httpBackend.flush();
});
});
It's failing on line 11. Here's what I see in my logs.
LOG: function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) { ... }
Chrome 36.0.1985 (Mac OS X 10.9.4) Basics should complete this task FAILED
TypeError: undefined is not a function
at null.<anonymous> (/path/to/app/main/httptest.js:11:30)
Chrome 36.0.1985 (Mac OS X 10.9.4): Executed 1 of 1 (1 FAILED) ERROR (0.023 secs / 0.021 secs)
What am I missing?
[EDIT: Here's where I went wrong... I was treating $httpBackend as though it were a mock of $http, when it's not. The following code succeeds.]
describe('Basics', function() {
var httpBackend;
var http;
beforeEach(angular.mock.inject(function($httpBackend, $http) {
httpBackend = $httpBackend;
http = $http;
httpBackend.when("GET", "/foo.json").respond("{\"name\":\"value\"}");
}));
it('should complete this task', function() {
console.log(httpBackend);
var getFoo=http.get("/foo.json") // line 11
.success(function(data) {})
.error(function() {});
httpBackend.flush();
})
});
Upvotes: 0
Views: 439
Reputation: 341
As far as the documentation for $httpBackend says, then you cannot use a method called "get". "get" is only when using $http
You should instead use "expectGet"
httpBackend.expectGET('/foo.json');
Upvotes: 1