业力/ angularjs如何测试与服务运行块 [英] karma/angularjs how to test run block with service

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

问题描述

这后跟随<一个href=\"http://stackoverflow.com/questions/25363969/karma-angularjs-how-to-test-run-block-with-an-asynchronous-service\">this
我已经张贴了其他线程具有容易
例如:

code测试

 使用严格的;    VAR应用= angular.module('对myApp',[]);
    app.run(函数($ rootScope,菜单){        VAR菜单= [
        {
            '许可':空,
            '标题':'家',
            链接:家
        },
        {
            '许可':'用户',
            标题:用户,
            '链接':'user_actions.list
        }
        ];        $ rootScope.menus = [];        功能queryMenu(菜单){
            Menus.query(菜单)。然后(
                功能(结果){
                    $ rootScope.menus = result.data;
                },
                函数(原因){
                    抛出新的错误(原因);
                }
                );
        }
        $ rootScope.valueSetInRun = 555;
        queryMenu(菜单);
    });
    app.factory('菜单',函数($ HTTP){
        返回{
            查询:功能(菜单){
                返回$ http.get('menus.json');
            }
        };
    });
    app.factory('UserFactory',函数($ HTTP){
        返回$ http.get('users.json')
    });
    app.controller('MainCtrl',函数($范围,UserFactory){
        $ scope.users = [];
        $ scope.text =世界,你好!;
        UserFactory.then(功能(数据){
            $ scope.users =数据。数据;
        });
    });

测试

 使用严格的;描述(运行,函数(){
    beforeEach(模块('对myApp'));
   变量$ httpBackend;
    beforeEach(注(函数($ rootScope,_ $ httpBackend_){
        $ httpBackend = _ $ httpBackend_;
        的console.log('beforeEach');
    }));   afterEach(函数(){
        $ httpBackend.verifyNoOutstandingExpectation();
        $ httpBackend.verifyNoOutstandingRequest();
    });    它('应该让我测试的run()堵',注入(函数($ rootScope,$ httpBackend){
        的console.log('它阻止');
        //不工作来看看http://stackoverflow.com/questions/25363969/karma-angularjs-how-to-test-run-block-with-an-asynchronous-service
        $ httpBackend.when('GET','menus.json')响应([{ID:1,名称:'鲍勃'},{ID:2,名称:'简'}]);
       $ httpBackend.flush();
       期待($ rootScope.valueSetInRun).toBe(555);
       的console.log($ rootScope.menus);
  }));
});描述(MainCtrl',函数(){
    VAR范围,$ httpBackend; //我们将在我们的测试中使用这些    //模拟应用,使我们能够注入我们自己的依赖
    beforeEach(模块('对myApp'));
    //模拟出于同样的原因,控制器和包括$ rootScope和$控制器
    beforeEach(注(函数($控制器,_ $ rootScope_,_ $ _ httpBackend){
        $ httpBackend = _ $ httpBackend_;        $ httpBackend.when('GET','users.json')响应([{ID:1,名称:'鲍勃'},{ID:2,名称:'简'}]);        //创建一个空的范围
        范围= _ $ rootScope _ $新的()。
        //声明控制器,并注入我们的空范围
        $控制器('MainCtrl',{$范围:适用范围});
        $ httpBackend.flush();
    }));    afterEach(函数(){
        $ httpBackend.verifyNoOutstandingExpectation();
        $ httpBackend.verifyNoOutstandingRequest();
    });    它('应该有可变文本=的Hello World!',函数(){
       期待(scope.text).toBe(的'Hello World!');
    });    它('应该获取用户列表',函数(){
       //expect(scope.users.length).toBe(2);
       //expect(scope.users[0].name).toBe('Bob');
    });
});

这是给我这个错误

  **错误:意外的请求:GET menus.json
没有更多的要求预期**

END UP见@scarIz

的批复

  beforeEach(模块('对myApp'));
变量$ httpBackend;
beforeEach(注(功能(_ $ httpBackend_){
    $ httpBackend = _ $ httpBackend_;
    $ httpBackend.when('GET','menus.json')。响应([{
        ID:1,
        名称:'鲍勃'
    }])
    $ httpBackend.flush();
}));
afterEach(函数(){
    $ httpBackend.verifyNoOutstandingExpectation();
    $ httpBackend.verifyNoOutstandingRequest();
});
描述('INIT',函数(){    描述(MainCtrl',函数(){
        VAR范围,$ httpBackend,$ rootScope; //我们将在我们的测试中使用这些        //模拟应用,使我们能够注入我们自己的依赖        //模拟出于同样的原因,控制器和包括$ rootScope和$控制器
        beforeEach(注(函数($控制器,_ $ rootScope_,_ $ _ httpBackend){
            $ httpBackend = _ $ httpBackend_;            $ httpBackend.when('GET','users.json')。响应([{
                ID:1,
                名称:'鲍勃'
            },{
                ID:2,
                名称:'简'
            }]);
            $ rootScope = _ $ rootScope_;
            //创建一个空的范围
            范围= _ $ rootScope _ $新的()。
            //声明控制器,并注入我们的空范围
            $控制器('MainCtrl',{
                $适用范围:适用范围
            });
            $ httpBackend.flush();
        }));        afterEach(函数(){
            $ httpBackend.verifyNoOutstandingExpectation();
            $ httpBackend.verifyNoOutstandingRequest();
        });        它('应该有可变文本=的Hello World!',函数(){
            期待(scope.text).toBe(的'Hello World!');
        });        它('应该获取用户列表',函数(){
            期待(scope.users.length).toBe(2);
            期待(scope.users [0]。名称).toBe('鲍勃');
             期待($ rootScope.valueSetInRun).toBe(555);
           的console.log($ rootScope.menus);
        });
    });
});


解决方案

原因你的错误是, Menus.query 将每次的<执行测试之前运行code>对myApp 模块,它被称为是模块的 .RUN()配置。当您提供您的运行测试套件后端的定义,你有没有为 MainCtrl 这样做了。

因此​​,要解决这个问题,你可能需要使用运行前,之前被列入每一个测试,这应该在帮助文件中定义一个全局 beforeEach 块您的规格:

  beforeEach(注(函数($ httpBackend){
  $ httpBackend.when('GET','menus.json')响应([{ID:1,名称:'鲍勃'}])。
  $ httpBackend.flush();
}));

This post follow this I've posted an other thread with a easier example

code to test

 'use strict';

    var app = angular.module('myApp', []);
    app.run(function ($rootScope, Menus) {

        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);
                }
                );
        }
        $rootScope.valueSetInRun = 555;
        queryMenu(menus);
    });
    app.factory('Menus',  function($http) {
        return {
            query : function(menus){
                return $http.get('menus.json');
            }
        }; 
    });
    app.factory('UserFactory', function($http){
        return $http.get('users.json')
    });
    app.controller('MainCtrl', function($scope, UserFactory) {
        $scope.users = [];
        $scope.text = 'Hello World!';
        UserFactory.then(function(data){
            $scope.users =  data.data;
        });
    });

test

'use strict';

describe('Run', function() {
    beforeEach(module('myApp'));
   var $httpBackend;
    beforeEach(inject(function($rootScope,_$httpBackend_) {
        $httpBackend = _$httpBackend_;
        console.log('beforeEach');
    }));

   afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should allow me to test the run() block', inject(function ($rootScope,$httpBackend) {
        console.log('it block');
        // Doesn't work take a look at http://stackoverflow.com/questions/25363969/karma-angularjs-how-to-test-run-block-with-an-asynchronous-service
        $httpBackend.when('GET', 'menus.json').respond([{id: 1, name: 'Bob'}, {id:2, name: 'Jane'}]);
       $httpBackend.flush();
       expect( $rootScope.valueSetInRun ).toBe(555);
       console.log($rootScope.menus);
  }));
}); 

describe('MainCtrl', function(){
    var scope, $httpBackend;//we'll use these in our tests

    //mock Application to allow us to inject our own dependencies
    beforeEach(module('myApp'));
    //mock the controller for the same reason and include $rootScope and $controller
    beforeEach(inject(function( $controller,_$rootScope_, _$httpBackend_){
        $httpBackend = _$httpBackend_;

        $httpBackend.when('GET', 'users.json').respond([{id: 1, name: 'Bob'}, {id:2, name: 'Jane'}]);

        //create an empty scope
        scope = _$rootScope_.$new();
        //declare the controller and inject our empty scope
        $controller('MainCtrl', {$scope: scope});
        $httpBackend.flush();
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should have variable text = "Hello World!"', function(){
       expect(scope.text).toBe('Hello World!'); 
    });

    it('should fetch list of users', function(){
       //expect(scope.users.length).toBe(2);
       //expect(scope.users[0].name).toBe('Bob');
    });
});

that give me this error

**Error: Unexpected request: GET menus.json
No more request expected**

END UP see the reply of @scarIz

beforeEach(module('myApp'));
var $httpBackend;
beforeEach(inject(function( _$httpBackend_) {
    $httpBackend = _$httpBackend_;
    $httpBackend.when('GET', 'menus.json').respond([{
        id: 1, 
        name: 'Bob'
    }])
    $httpBackend.flush();
}));
afterEach(function() {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});
describe('Init', function() {

    describe('MainCtrl', function(){
        var scope, $httpBackend,$rootScope;//we'll use these in our tests

        //mock Application to allow us to inject our own dependencies

        //mock the controller for the same reason and include $rootScope and $controller
        beforeEach(inject(function( $controller,_$rootScope_, _$httpBackend_){
            $httpBackend = _$httpBackend_;

            $httpBackend.when('GET', 'users.json').respond([{
                id: 1, 
                name: 'Bob'
            }, {
                id:2, 
                name: 'Jane'
            }]);
            $rootScope = _$rootScope_;
            //create an empty scope
            scope = _$rootScope_.$new();
            //declare the controller and inject our empty scope
            $controller('MainCtrl', {
                $scope: scope
            });
            $httpBackend.flush();
        }));

        afterEach(function() {
            $httpBackend.verifyNoOutstandingExpectation();
            $httpBackend.verifyNoOutstandingRequest();
        });

        it('should have variable text = "Hello World!"', function(){
            expect(scope.text).toBe('Hello World!'); 
        });

        it('should fetch list of users', function(){
            expect(scope.users.length).toBe(2);
            expect(scope.users[0].name).toBe('Bob');
             expect( $rootScope.valueSetInRun ).toBe(555);
           console.log($rootScope.menus);
        });
    });
}); 

解决方案

The reason for your error is that Menus.query will run before every test you perform for the myApp module as it's called in the module's .run() configuration. While you have provided a backend definition in your Run test suite, you have not done so for MainCtrl.

Therefore, to counter this, you might want to use a global beforeEach block that runs before every test, which should be defined in a helper file to be included prior to your specs:

beforeEach(inject(function($httpBackend) {
  $httpBackend.when('GET', 'menus.json').respond([{id: 1, name: 'Bob'}])
  $httpBackend.flush();
}));

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

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