【问题标题】:unit testing a recursive http request with angular httpbackend使用角度 httpbackend 对递归 http 请求进行单元测试
【发布时间】:2014-08-20 23:54:00
【问题描述】:

我正在使用他们的 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 进行无限请求的一种方式?

【问题讨论】:

    标签: angularjs unit-testing httpbackend


    【解决方案1】:

    当您的测试预计对同一 URL 的多个请求时,应使用 $httpBackend.when 方法套件。

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        • 1970-01-01
        • 2023-03-20
        • 2017-06-05
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        相关资源
        最近更新 更多