如何在angularjs中进行单元测试时模拟$ location

Cha*_*dra 7 unit-testing angularjs

这是我的运行块,我rootScope根据位置路径设置了几个属性:

angular.module('xyz').run(['$rootScope', '$location', '$route', function($rootScope, $location, $route){
    $rootScope.brand = $location.path().split('/')[1];
    $rootScope.appName = $rootScope.brand.split('.')[2];
});
Run Code Online (Sandbox Code Playgroud)

这是失败的单元测试:

beforeEach(module('App'));

beforeEach( inject( function( $controller, _$location_, $rootScope) {
    $location = _$location_;
    $scope = $rootScope.$new();
    AppCtrl = $controller( 'AppCtrl', { $location: $location, $scope: $scope });
}));
it('AppCtrl has been initialized', inject( function() {
    expect( AppCtrl ).toBeTruthy();
}));
Run Code Online (Sandbox Code Playgroud)

沿着这些方向尝试了一些事情:

it('should set the default category to match the category_id found in location.hash', function() {
    $browser.setUrl('http://server/#/categories/2');
    $browser.poll();
    scope.$eval();
    $browser.xhr.flush();
    expect(ctrl.selectedCategory).toBe('2'); 
}); 
Run Code Online (Sandbox Code Playgroud)

没有帮助.

Cai*_*nha 6

以下是您的解决方案https://groups.google.com/d/msg/angular/F0jFWC4G9hI/FNz3oQu0RhYJ.

只是为了让您知道,Igor Minar和VojtaJína都是Angular开发人员,后者是AngularJs单元测试背后的主要人物之一,所以要注意它们.

所以,基本上它$location在测试时已经使用了服务的模拟版本,你应该能够完美地控制它.

  • 谢谢你的贡献.虽然对SO的快速总结可能有所帮助:它使您的答案质量更可靠,内容更容易访问. (7认同)