单元测试带有角度httpbackend的递归http请求

时间:2014-06-30 14:56:41

标签: angularjs unit-testing httpbackend

我正在使用他们的jasmine和karma设置对我的AngularJS应用进行单元测试。我一直在使用AngularJS mock $httpbackend

https://docs.angularjs.org/api/ngMock/service/$httpBackend

我遇到的问题是测试以下模块:

define([
    'angular',
    'app',
    'angularRoute',
    ], function (angular, app) {
        'use strict';

        app.config(function ( $httpProvider) {        
            /* Angular automatically adds this header to the request,
               preventing us from being able to make requests to the server on another port */
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }).factory('equipmentService', ['$http', '$rootScope', function($http, $rootScope) {
            var factory = {
                setEquipmentState: function(state){
                    this.equipmentState = state.state;
                    console.log('equipment state', this.equipmentState);
                    redirectState(this.equipmentState);
                }
            }
            var redirectState = function (state) {
                switch(state) {
                    case 'Active':
                        $location.path('/active');
                        break;
                    case 'Review':
                        $location.path('/review');
                        break;
                    default:
                        // don't change views
                }
            }

            function stateCheck () {
                $http.get($rootScope.backendServer+'/equipment/state/changed')
                .then(function (data) {
                    factory.setEquipmentState(data.data);
                })
                .then(stateCheck);
            }

            stateCheck();


            return factory;
        }]);
});

我总是向服务器发出待处理的http请求;一旦服务器响应,发送另一个http请求。因此,即使我的模拟httpbackend期待请求,一旦响应,我也不知道如何避免错误:

  

错误:意外请求:获取网址       不再需要预期

我有办法忽略此特定请求的此错误吗?或者模拟httpbackend的方式是期望对该URL的无限请求?

2 个答案:

答案 0 :(得分:2)

当您的测试期望对同一个网址发出多个请求时,应该使用$httpBackend.when方法套件。

https://docs.angularjs.org/api/ngMock/service/$httpBackend

答案 1 :(得分:0)

您应该使用$httpBackend.expect$httpBackend.when的组合来涵盖可能多次发生的必需通话:

$ httpBackend.expectPUT(' URI')...(使其成为必需) $ httpBackend.whenPUT(' URI')...(允许多次通话)