来自自定义服务单元测试中的意外 HTTP GET 调用

Unexpected HTTP GET calls from within a custom Service unit test

嗯,我的问题很简单,在标题中有描述。我有一个虚拟服务,我想以 TDD 方式实现它。

我打算将我的实现转向使用 $http 服务和 deferred+promises。这将需要测试代码中的 $scope().$apply() 。因此,一旦我添加了这个调用,我就观察到了意外的 HTTP GET 调用,这些调用试图检索我的项目中存在的所有模板 html。

PhantomJS 1.9.8 (Windows 8 0.0.0) myService should search places just fine FAILED
    Error: Unexpected request: GET app/landing/landing.html
    No more request expected
        at $httpBackend (c:/workspace/ionic/myApp/www/lib/angular-mocks/angular-mocks.js:1245)
        at sendReq (c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:23514)
        at c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:23225
        at processQueue (c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:27747)
        at c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:27763
        at c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:29026
        at c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:28837
        at c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:29131
        at c:/workspace/ionic/myApp/tests/services/myServiceSpec.js:35
        at invoke (c:/workspace/ionic/myApp/www/lib/ionic/js/ionic.bundle.js:17630)
        at workFn (c:/workspace/ionic/myApp/www/lib/angular-mocks/angular-mocks.js:2439)
    undefined

知道为什么会这样吗?我打赌 angular 开发者的 Nooby 问题...

我的简单服务甚至不调用 $state.go()。

(function () {
    'use strict';

    angular.module('myApp').factory('myService', ['$q', '$http', myService]);

    function myService($q, $http) {
        var service = this;

        function searchPlacesAsync() {
            var placesList = [
                { userName: 'Mister X', title: 'Haunted places' },
                { userName: 'Mister A', title: 'Cute places' },
                { userName: 'Mister S', title: 'Lovely places' }
            ];

            var deferred = $q.defer();
            deferred.resolve(placesList);
            return deferred.promise;
        };

        return {
            searchPlacesAsync: searchPlacesAsync
        };
    };
})();

单元测试

describe('myService', function(){
    var myService,
        $scope;

    beforeEach(module('myApp'));

    beforeEach(inject(function (_myService_, _$rootScope_){
        myService = _myService_;
        $scope = _$rootScope_.$new();
    }));

    it('should search places just fine', inject( function($httpBackend){
        // Arrange
        var placesFilter = { location: { country: 'Russia', city: 'Moscow'} };
        myService.setFilter(placesFilter);

       // TODO Why should I do it
       $httpBackend.whenGET('app/search_places/searchPlaces.html').respond({});
        //$httpBackend.whenGET('app/landing/landing.html').respond({});
        // Act
        var result = myService.searchPlacesAsync();
        $scope.$apply();
        // Assert
        expect(result).not.toBe(null);
    }) );
});

最后,这是我的 Karma 配置文件

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
        '../www/lib/ionic/js/ionic.bundle.js',
        '../www/lib/angular-mocks/angular-mocks.js',
        '../www/lib/angular/angular.js',
        '../www/lib/ionic-wizard/dist/ion-wizard.min.js',
        '../www/app/**/*.js',
        '**/*Spec.js'
    ],
    exclude: [],
    preprocessors: {},
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: false,
    concurrency: Infinity
  })
}

更新 这是我的app.js 文件

angular.module('myApp', ['ionic', 'ionic.wizard'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {

    if (window.cordova && window.cordova.plugins.Keyboard) {
  // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
      // for form inputs)
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);

      // Don't remove this line unless you know what you are doing. It stops the viewport
      // from snapping when text inputs are focused. Ionic handles this internally for
      // a much nicer keyboard experience.
      cordova.plugins.Keyboard.disableScroll(true);
    }

    if (window.StatusBar) {
      StatusBar.styleDefault();
    }

  });
})

.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('landing', {
      // abstract: true,
      url: '/landing',
      templateUrl: 'app/landing/landing.html'
    })

    .state('user_wizard', {
      url: '/user/wizard',
      templateUrl: 'app/user_wizard/userWizard.html'
    })

    .state('provider_wizard', {
      url: '/provider/wizard',
      template: 'provider WIZARD...'
    })

    .state('search_places', {
      url: '/search/places',
      templateUrl: 'app/search_places/searchplaces.html'
    })

    .state('view_Place', {
      url: '/places/view/:id',
      templateUrl: 'app/view_place/viewPlace.html'
    });

  $urlRouterProvider.otherwise('/search/places');
}]);

我认为您的主要问题是您正在使用 $scope.$apply() 使您的服务 return 成为未决值。相反,您可以只使用 $httpBackend.flush() 强制后端解决任何未决请求并解决其承诺。这应该可以解决您的模板获取问题。

For this reason, the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests. This preserves the async api of the backend, while allowing the test to execute synchronously.

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

但是,您稍后可能会 运行 再次参与其中。当你这样做时,你必须告诉 $httpBackend 对每个模板响应什么。这是手工无法完成的任务。相反,请使用 Karma 中的 ng-html2js 预处理器,它会自动获取您的 html,并将其编译成适当的 Javascript 字符串。然后,您可以创建一组可作为模块使用的模板。我只有一个巨大的,其中包含所有这些,我将其包含在需要它们的测试中。

Unit Testing AngularJS directive with templateUrl <== 查看第一个答案以获得业力预处理器的帮助