gpt4 book ai didi

javascript - AngularJs Jasmine 单元测试中的 $httpBackend

转载 作者:数据小太阳 更新时间:2023-10-29 04:40:30 25 4
gpt4 key购买 nike

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

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

但 jasmine 的错误是:Expected 0 to be 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

最佳答案

您需要在 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);
} );

试试这个。

关于javascript - AngularJs Jasmine 单元测试中的 $httpBackend,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25775462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com