0

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 は作品から http 応答を取得します$httpBackendが、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();
});

なぜそれが機能しないのですか?

これはjsFiddleのデモです。

4

1 に答える 1

1

$httpBackend.flush()後に呼び出すstop()とうまくいきます:

stop();
$httpBackend.flush();

これが更新されたデモです。

于 2014-03-20T19:49:33.800 に答える