AngularJs Jasmine单元测试中的$ httpBackend

时间:2014-09-10 21:34:54

标签: javascript angularjs unit-testing jasmine

我无法让我的单元测试正常工作。我有一个$ scope数组,它开始是空的,但应该用$ http.get()填充。在真实环境中,阵列中大约有15个左右的对象,但是对于我的单元测试,我只抓了2.对于单元测试,我有:

expect($scope.stuff.length).toBe(2);

但茉莉花的错误是:预期0为2。

这是我的controller.js:

$scope.stuff = [];
$scope.getStuff = function () {
    var url = site.root + 'api/stuff';
    $http.get(url)
        .success(function (data) {
            $scope.stuff = data;
        })
        .error(function(error) {
            console.log(error);
        });
};

我的controller.spec.js是:

/// <reference path="../../../scripts/angular-loader.min.js" />
/// <reference path="../../../scripts/angular.min.js" />
/// <reference path="../../../scripts/angular-mocks.js" />
/// <reference path="../../../scripts/angular-resource.js" />
/// <reference path="../../../scripts/controller.js" />
beforeEach(module('ui.router'));
beforeEach(module('ngResource'));
beforeEach(module('ngMockE2E'));
beforeEach(module('myApplication'));
var $scope;
var controller;
var httpLocalBackend;

beforeEach(inject(function ($rootScope, $controller, $injector) {
    $scope = $rootScope.$new();
    controller = $controller("StuffController", {
        $scope: $scope
    });
}));

beforeEach(inject(function ($httpBackend) {
    httpLocalBackend = $httpBackend;
}));

it('should get stuff', function () {
    var url = '/api/stuff';
    var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }];
    httpLocalBackend.expectGET(url).respond(200, httpResponse);
    $scope.getStuff();
    expect($scope.stuff.length).toBe(2);
    //httpLocalBackend.flush();
} );

现在,很明显,我更改了变量名称,因为这是为了工作,但希望这对任何人都有足够的信息来帮助我。如果需要,我可以提供更多。取消注释.flush()行时,我也会遇到第二个错误,但稍后我会稍等。

非常感谢任何帮助,并提前致谢!

编辑:

终于搞定了!这是我的最终代码:

it('should get stuff', function () {
    var url = '/api/stuff';
    var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }];
    httpLocalBackend.expectGET(url).respond(200, httpResponse);
    $scope.getStuff();
    httpLocalBackend.flush();
    expect($scope.stuff.length).toBe(2);
} );

编辑2: 我遇到了另一个问题,我认为可能是这个问题的根本原因。见Unit test failing when function called on startup

1 个答案:

答案 0 :(得分:7)

您需要在expect($ scope.stuff.length).toBe(2)之前放置httpLocalBackend.flush()语句。一旦您提出请求,您需要刷新它以使数据在您的客户端代码中可用。

it('should get stuff', function () {
    var url = '/api/roles';
    var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }];
    scope.getStuff(); //Just moved this from after expectGET
    httpLocalBackend.expectGET(url).respond(200, httpResponse);
    httpLocalBackend.flush();
    expect($scope.stuff.length).toBe(2);
} );

试试这个。