gpt4 book ai didi

javascript - 在尝试测试返回的数据之前,如何对 PhantomJS 进行编程以等待 AngularJS $resource 解析?

转载 作者:行者123 更新时间:2023-11-28 00:56:38 25 4
gpt4 key购买 nike

我有一个使用 PhantomJS 的 AngularJS Controller 测试脚本。该测试查看 Controller 是否已使用 AngularJS 的 $resource 服务通过 RESTFul Web 服务从数据库加载“用户”数据。问题是测试失败,因为测试执行时 $resource (我相信它返回一个 promise )尚未解决。处理这种延迟以使测试通过的正确方法是什么?这是我的代码:

Controller :

.controller('MainCtrl', function ($scope, Users) {
$scope.users = Users.query();
$scope.sortField = 'lastName';
$scope.reverseSort = true;
})

服务:

angular.module('clearsoftDemoApp').factory('Users', function ($resource) {
return $resource('http://localhost:8080/ClearsoftDemoBackend/webresources/clearsoft.demo.users', {}, {
query: {method: 'GET', isArray: true}
});
});

测试:

describe('Controller: MainCtrl', function () {

// load the controller's module
beforeEach(module('clearsoftDemoApp'));

var MainCtrl, scope;

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
});
}));

it('should retrieve a list of users and assign to scope.users', function () {
expect(scope.users.length).toBeGreaterThan(0);
});
});

最佳答案

您需要模拟工厂调用并将模拟传递给 Controller ​​:

beforeEach(inject(function ($controller, $rootScope) {
var users = { query: function() { return [{}]; } };
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Users: users
});
}))

关于javascript - 在尝试测试返回的数据之前,如何对 PhantomJS 进行编程以等待 AngularJS $resource 解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26147698/

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