一个程序PhantomJS如何等待AngularJS$资源解析,然后再尝试测试返回的数据

How does one program PhantomJS to wait for AngularJS $resource to resolve before attempting test on returned data?

本文关键字:然后 数据 返回 测试 程序 一个 PhantomJS AngularJS 等待 何等待 资源      更新时间:2023-09-26

我有一个使用PhantomJS的AngularJS控制器测试脚本。该测试旨在查看控制器是否通过使用AngularJS的$resource服务的RESTFul web服务从数据库加载了"用户"数据。问题是测试失败是因为$resource(我相信它返回了一个promise)在测试执行时还没有得到解决。为了通过考试,应对这种延误的正确方法是什么?这是我的代码:

控制器

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

您需要模拟工厂调用并将模拟传递给控制器:

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