gpt4 book ai didi

javascript - AngularJS Jasmine 测试: scoped variable always undefined

转载 作者:行者123 更新时间:2023-11-28 01:24:04 25 4
gpt4 key购买 nike

我对 Javascript 测试非常陌生,目前正在尝试测试 Controller 功能。该函数调用从 Web SQL 数据库检索数据的服务方法。

这是我的 Controller 函数的一部分(它包含 2 个回调,一个用于成功,另一个用于错误):

    $scope.getLocations = function () {
LocationDbService.getAll(
//Success
function (tx, results) {

$scope.numberOfLocations = results.rows.length;
...
},
//Error
function () {
console.log("Error");
});
}

测试:

it('we should be able to retrieve all stored locations',
function () {
expect(scope.numberOfLocations).toBeUndefined();
scope.getLocations();
expect(scope.numberOfLocations).toBeDefined();
});

每次测试之前:

var ctrl, scope, location, locationDbService;
// inject the $controller and $rootScope services
// in the beforeEach block
beforeEach(inject(function ($controller, $rootScope, $location, LocationDbService) {
// Create a new scope that's a child of the $rootScope
scope = $rootScope.$new();
// Create the controller
ctrl = $controller('LocationsCtrl', {
$scope: scope
});
location = $location;
locationDbService = LocationDbService;
}));

Controller header :

.controller('LocationsCtrl', function ($scope, $location, LocationDbService) {

当我在浏览器中运行应用程序(或在我的智能手机上,它是一个混合应用程序)时,一切正常,但当我运行测试时,我得到以下结果:

Test failure

有人知道为什么作用域变量仍未定义吗?预先感谢!

最佳答案

实例化 Controller 时,您还应该注入(inject)它需要的任何其他服务。

AngularJS 有一个很酷的技巧,你可以在名称中使用下划线:

  beforeEach(inject(function ($controller, $rootScope, _$location_, _LocationDbService_) {
// Create a new scope that's a child of the $rootScope
scope = $rootScope.$new();
// Create the controller
ctrl = $controller('LocationsCtrl', {
$scope: scope,
$location : _$location_,
LocationDbService : _LocationDbService_
});
location = _$location_; //thx to the underscores you could use '$location' as name instead of 'location'
locationDbService = _LocationDbService_;
}));

接下来您应该模拟服务调用:

it('should be able to retrieve all stored locations',
function () {
spyOn(locationDbService , 'getAll').andCallFake(function (success, fail) {
var results = {};
results.rows = new Array(5);
success(null, results);
});
expect(scope.numberOfLocations).toBeUndefined();
scope.getLocations();
expect(scope.numberOfLocations).toBe(5);
});

该服务应该有自己的测试。

关于javascript - AngularJS Jasmine 测试: scoped variable always undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22931474/

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