0

我在学习使用 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();
    })
});
4

1 回答 1

1

就 $httpBackend 的文档而言,您不能使用名为“get”的方法。"get" 仅在使用 $http 时

您应该改用“expectGet”

httpBackend.expectGET('/foo.json');
于 2014-08-15T17:42:03.670 回答