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

Javascript 来自自定义服务单元测试中的意外HTTP GET调用,javascript,angularjs,unit-testing,karma-runner,angular-services,Javascript,Angularjs,Unit Testing,Karma Runner,Angular Services,嗯,我的问题很简单,在标题中有描述。我有一个虚拟服务,我想以TDD方式实现它 我将把我的实现转向使用$http服务和延迟+承诺。这需要在测试代码中使用$scope().$apply()。所以,当我添加这个调用时,我观察到意外的HTTPGET调用,这些调用试图检索项目中存在的所有模板HTML PhantomJS 1.9.8 (Windows 8 0.0.0) myService should search places just fine FAILED Error: Unexpected

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

我将把我的实现转向使用$http服务和延迟+承诺。这需要在测试代码中使用$scope().$apply()。所以,当我添加这个调用时,我观察到意外的HTTPGET调用,这些调用试图检索项目中存在的所有模板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
你知道为什么会这样吗?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()
使您的服务返回它的挂起值。相反,您可以使用
$httpBackend.flush()
强制后端解决任何挂起的请求并解决其承诺。这应该可以解决模板获取的问题

因此,mock$httpBackend有一个flush()方法,该方法允许测试显式地刷新挂起的请求。这将保留后端的异步api,同时允许同步执行测试。

但是,您以后可能会再次遇到这种情况。当您这样做时,您必须告诉$httpBackend每个模板要响应什么。这是一项不可能手工完成的任务。取而代之的是使用Karma中的ng-html2js预处理器,它会自动获取html,并将其编译成适当的Javascript字符串。然后,您可以创建一组模板作为模块提供。我只是有一个巨大的一个,里面有所有的,我包括在需要它们的测试中


谢谢你的快速回复。我将
$scope.$apply()
替换为
$httpBackend.flush()
,但这并没有影响单元测试行为:我仍然收到此
错误:意外请求:获取app/landing/landing.html
。你能给我一个提示,为什么会有这样的要求?该服务对通过此GET请求请求的模板相关的任何内容都没有任何明确的依赖关系。我认为您仍然从
\u$rootScope.$new()
获取模板请求。请尝试删除该请求。不,这不再是我的代码的一部分。这就是我仍然困惑的地方。@IgorSoloydenko我得去睡觉了。如果可以,发布index.js以及新代码。我想知道是否仅仅包括
模块('myApp')
就导致了整个事情的评估,并且您的index.js中包含了某种模板。事实上,如果您可以在浏览器中调试单元测试,并逐步执行,直到对模板进行ajax调用,这可能会对您有很大帮助。这样你就可以找出是哪一行引起的。我强烈建议你试试我推荐的调试步骤。老实说,在这一点上,我很困惑是什么导致了这个请求。不幸的是,你的index.js没有给我任何启示:(除非ui路由器主动执行模板请求。也许你可以试着注释ui路由器的路由配置,看看这是否会阻止它)。