AngularJS $ httpBackend expectGET无效

时间:2014-03-18 00:02:59

标签: angularjs qunit angular-mock

我正在为AngularJS工厂编写QUnit测试。这是工厂的代码:

var app = angular.module('App', []);
app.factory('$groupFactory', function($rootScope, $http) {
    return {
        'getAll': function(_callback) {
            $http.get("get/values/from/server", {
                headers: {
                    'Content-type': 'application/json'
                }
            }).success(function(data, status, headers, config) {
                _callback(data);
            }).
            error(function(data, status, headers, config) {
                _callback(data);
            });
        },
    }
});

另见下面的Qunit测试用例。 test-1从$httpBackend得到http响应,但在test-2中,它没有。

var $scope,
    $rootScope,
    $http,
    $httpBackend,
    $groupFactory,
    injector = angular.injector(['ng', 'App', 'ngMockE2E']),
    init;
init = {
    setup: function() {
        $rootScope = injector.get('$rootScope').$new();
        $groupFactory = injector.get('$groupFactory');
        $httpBackend = injector.get('$httpBackend');
        $httpBackend
            .when('GET', "get/values/from/server")
            .respond({'response': 'success'});
    }
};

module('$groupFactory', init);

// test-1
test("getAll", function() {
    expect(1);
    $groupFactory.getAll(function(data) {
        equal(data.response, 'success', "success casse");
        start();
    });
    stop();
});

// test-2
test("getAll", function() {
    expect(1);
    $httpBackend.expectGET("get/values/from/server").respond(404, {
        response: 'failure'
    });
    $groupFactory.getAll(function(data) {
        equal(data.response, 'failure', "failure casse");
        start();
    });
    stop();
});

知道为什么它不起作用?

这是demo on jsFiddle

1 个答案:

答案 0 :(得分:1)

$httpBackend.flush()之后调用stop()将起作用:

stop();
$httpBackend.flush();

这里是updated demo