AngularJs Jasmine单元测试中的$httpBackend

$httpBackend in AngularJs Jasmine unit test

本文关键字:httpBackend Jasmine 单元测试 AngularJs      更新时间:2023-09-26

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

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

但是jasmine的错误是:0应该是2。

这是我的控制器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);
        });
};

我的控制器.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:我遇到了另一个问题,我认为这可能是造成这种情况的根本原因。请参阅在启动时调用函数时单元测试失败

您需要将httpLocalBackend.flush()语句放在expect($scope.stuff.length).toBe(2)之前。发出请求后,您需要刷新它,以便在客户端代码中提供数据。

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);
} );

试试这个。