我有一个使用PhantomJS的AngularJS控制器测试脚本。测试看看控制器是否已加载"用户"使用AngularJS'来自数据库的数据通过RESTFul Web服务$资源服务。问题是测试失败是因为$ resource(返回我认为的承诺)在测试执行时尚未得到解决。什么是处理这种延迟的正确方法,以便测试通过?这是我的代码:
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}
});
});
TEST :
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);
});
});
答案 0 :(得分:1)
您需要模拟工厂调用并将模拟传递给控制器:
beforeEach(inject(function ($controller, $rootScope) {
var users = { query: function() { return [{}]; } };
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope,
Users: users
});
}))