我很难学习使用Karma对一些AngularJS代码进行单元测试,并且我对使用$ httpBackend感到困惑。我已经创建了测试的简化版本,仅显示模拟get请求的位置,并期望看到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();
});
});
它在第11行失败了。这就是我在日志中看到的内容。
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)
我错过了什么?
[编辑:这里我出错的地方......我正在对$ httpBackend进行处理,好像它是$ http的模拟,当时它不是。以下代码成功。]
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();
})
});
答案 0 :(得分:1)
就$ httpBackend的文档所说,那么你不能使用名为&#34; get&#34;的方法。 &#34;获得&#34;仅在使用$ http
时您应该使用&#34; expectGet&#34;
httpBackend.expectGET('/foo.json');