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

时间:2022-11-07 18:29:43

Here's my run block, where I set a couple of properties on rootScope based on the location path:

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

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

Here's the unit test that's failing:

这是失败的单元测试:

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();
}));

Tried something along these lines:

尝试过这些方面:

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'); 
}); 

Didn't help.

没有帮助。

1 个解决方案

#1


7  

Here is your solution https://groups.google.com/d/msg/angular/F0jFWC4G9hI/FNz3oQu0RhYJ.

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

Just to let you know, Igor Minar and Vojta Jína are both Angular developers and the latter is one of the main persons behind AngularJs unit testing, so pay attention to them.

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

So, basically it already uses a mocked version of the $location service while in test and you should be able to perfectly control it.

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

#1


7  

Here is your solution https://groups.google.com/d/msg/angular/F0jFWC4G9hI/FNz3oQu0RhYJ.

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

Just to let you know, Igor Minar and Vojta Jína are both Angular developers and the latter is one of the main persons behind AngularJs unit testing, so pay attention to them.

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

So, basically it already uses a mocked version of the $location service while in test and you should be able to perfectly control it.

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