业力/ angularjs如何使用异步服务试运行块 [英] karma/angularjs how to test run block with an asynchronous service

查看:207
本文介绍了业力/ angularjs如何使用异步服务试运行块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试,如:

angular.module('lama.system', [])
   .config(['$httpProvider', function($httpProvider) {
        // Crossdomain requests not allowed if you want do cors request see filter.php 
        $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    }])
    .run(['$rootScope', '$state', '$log', 'Global',function ($rootScope, $state, $log, Global) {
        $rootScope.$state = $state;
        $rootScope.$log = $log;
        $rootScope.global = Global;
    }]);

controllers.js lama.system模块

angular.module('lama.system')
    .controller('SystemController', ['$scope',
        function($scope) {
           $scope.test =[];

         }
    ]);

services.js lama.system模块

angular.module('lama.system')
    .factory('Menus', ['$http', function($http) {
        return {
            query : function(menus){
                return $http.get('/api/v1/user/menus', {
                    params: {
                        'menus[]': menus
                    }
                });
            }
        }; 
    }]);

system.js路由器

//Setting up route
angular.module('lama.system')
    .config(['$stateProvider', '$urlRouterProvider',
        function($stateProvider, $urlRouterProvider) {
            $urlRouterProvider.otherwise('/');
            $stateProvider              
            .state('home', {
                url: '/',
                templateUrl: 'system/views/home.html',
                controller:'SystemController'
            });
        }
    ]);

init.js喇嘛模块

angular.module('lama', ['ui.router','restangular','lama.system','lama.users'])
    .run(['$rootScope',  'Menus',function ($rootScope, Menus) {
       // Default hard coded menu items for main menu
           var menus = [
            {
                'permission': null,
                'title': 'Home',
                'link': 'home'
            },
            {
                'permission': 'users',
                'title': 'User',
                'link': 'user_actions.list'
            }
            ];

            $rootScope.menus = [];

            function queryMenu(menus) {
                Menus.query(menus).then(
                    function (result) {
                        $rootScope.menus = result.data; 
                    },
                    function (reason) {
                        throw new Error(reason);
                    }
                    );
            }

            // Query server for menus and check permissions
            queryMenu(menus);

           $rootScope.$on('loggedin', function(event,user) {
                console.log('kkk');
                queryMenu(menus);

                $rootScope.global = {
                    user:  user,
                    authenticated: user.groups.length,
                    isAdmin:  user.groups.indexOf('Admins')
                };
            });


    }]);

该测试

(function() {
    describe('Unit test: system module', function () {
        describe('SystemController', function () {

            // load the controller's module
            beforeEach(function() {
                module('lama');
                module('stateMock');
            });

            var SystemController,
            $rootScope,
            $scope,
            $httpBackend;

            // Initialize the controller and a mock scope
            beforeEach(inject(function ($controller, _$rootScope_, _$httpBackend_) {
                $rootScope = _$rootScope_;
                $scope = _$rootScope_.$new();
                $httpBackend = _$httpBackend_;
                SystemController = $controller('SystemController', {
                    $scope: $scope
                });
                $httpBackend.when('GET', '/api/v1/user/menus').respond(200,{});
            }));

            it('should attach a list of awesomeThings to the scope', function () {
                expect($scope.test.length).toBe(0);
            });

            it('should expose some global scope', function() {
                expect($rootScope.global).toBeTruthy();
            });
        });

    });
}());

的给我:(

grunt test
Running "karma:unit" (karma) task
INFO [karma]: Karma v0.12.21 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
WARN [watcher]: Pattern "/home/whisher/public_html/public/users/tests/unit/**/*.js" does not match any file.
INFO [PhantomJS 1.9.7 (Linux)]: Connected on socket zK1SplAjTHe4x5sAM9ew with id 16331650
WARN [web-server]: 404: /api/v1/user/menus?menus%5B%5D=%7B%22permission%22:null,%22title%22:%22Home%22,%22link%22:%22home%22%7D&menus%5B%5D=%7B%22permission%22:%22users%22,%22title%22:%22User%22,%22link%22:%22user_actions.list%22%7D
WARN [web-server]: 404: /system/views/home.html
ERROR: 'Error: [object Object]
    at http://localhost:9876/base/public/init.js?c7a481724bcf81e4810141349c93d0f698a18904:34
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:100
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:100
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:101
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:112
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:109
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:112
    at h (http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:72)
    at x (http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:77)
    at http://localhost:9876/base/public/bower_components/angular/angular.min.js?4b4cffd940f7a29168096212664973432d1d7449:78'
PhantomJS 1.9.7 (Linux): Executed 2 of 2 SUCCESS (0.039 secs / 0.065 secs)

Done, without errors.

NB

我使用的UI路由器

推荐答案

我已经采取看看你的源$ C ​​$ C。主要违规产品:

I've taken a look at your source code. The primary offending item is:

angular.element(document).ready(function() {
  angular.bootstrap(document, ['lama']);
});

通过在文件因缘进口的人工引导,您的应用程序是联合国必然被业力测试环境中自举。所以,相反,移动你的喇嘛模块放到一个单独的文件,并从文件中省略 init.js 被列入业力。

By including your manual bootstrap in the files that karma imports, your app is un-necessarily being bootstrapped within the karma test environment. So, instead, move your lama module into a separate file, and omit init.js from your files to be included by karma.

此外,还有一些其他方面的设计要求所导致过多的测试设置。测试时 SystemController 有没有需要包括什么,但 lama.system 模块(因为这是控制器属于哪个至)。测试设置此控制器可以是简单的:

There are also a couple of other design concerns that are causing excessive test setup. When testing SystemController there is no need to include anything but the lama.system module (as this is what the controller belongs to). Your test setup for this controller can be as simple as:

var $scope, $rootScope;

beforeEach(module('system.lama'));

beforeEach(inject(function($controller, _$rootScope_) {
  $rootScope = _$rootScope_;
  $scope = $rootScope.$new();
  $controller('SystemController', {$scope: $scope});
}));

您会注意到,在隔离 lama.system 模块如上,你会得到一个错误, $状态不能注射(未找到)。这是因为你的模块定义应该改为是:

You will note that in isolating the lama.system module as above, you will get an error that $state cannot be injected (not found). This is because your module definition should instead be:

angular.module('lama.system', ['ui.router'])

(A模块不应该需要另外一个模块为它自己的依赖的presence,否则不能孤立从未运行)。

(A module should not require the presence of another module for its own dependencies, else it can never function in isolation).

在你的嘲讽为喇嘛模块运行块最后一个观察。严格地说应该存根服务查询方法完全,不只是其实现的一部分,否则您的测试是完全隔离的。因此,相反,它会更好地做到以下几点:

One final observation on your mocking for the lama module run block. Strictly speaking you should stub the service query method entirely and not just part of its implementation, else your test is completely isolated. Therefore, instead, it would be better to do the following:

beforeEach(module(function($provide) {
  $provide.decorator('Menus', function($delegate, $q) {
     // overwrite the query method
     $delegate.query = function() {
       return $q.when([{id: 1, name: 'Bob'}]);
     };    
     return $delegate; 
  });
}));

这样,你并不需要在所有的担心使用 $ httpBackend

这篇关于业力/ angularjs如何使用异步服务试运行块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆