1

我正在使用他们的 jasmine 和 karma 设置对我的 AngularJS 应用程序进行单元测试。我一直在使用 AngularJS 模拟$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 期待请求,一旦它响应,我不知道如何避免错误:

错误:意外请求:GET url
没有更多请求

有没有办法让我忽略这个特定请求的这个错误?还是模拟 httpbackend 期望对该 url 的无限请求的一种方式?

4

2 回答 2

2

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

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

于 2014-10-30T23:56:22.233 回答
0

You should use a combination of $httpBackend.expect and $httpBackend.when to cover a required call that can happen multiple times:

$httpBackend.expectPUT('URI')... (makes it required) $httpBackend.whenPUT('URI')... (allows for multiple calls)

于 2015-03-10T10:41:08.787 回答