AngularJS Karma check url param 是存在的



我是单元测试的新手,并尝试为我的应用程序编写单元测试。我的路线是:

{
name: 'details',
url: '/accounts/company/:companyId',
controller: 'controllere',
templateUrl: 'templateurl',
}

我的控制器 :

if (!$stateParams.companyId) {
$scope.promise = $state.go('home');
} else {
// get company details
}

在我的单元测试中,我需要测试URL中是否存在"companyId",然后只继续其余的重定向到"主页"。我尝试了这段代码,但每次都失败。我不知道我做错了什么。

it('should respond to URL with params', function() {
expect($state.href('/accounts/company/', { companyId: 'test-company' })).toEqual('#/accounts/company/test-company');
});

每次我运行此测试时,它都会说:预期空值等于"#/帐户/公司/测试公司"。

$state.href方法期望stateName如第一个参数,后跟参数需要形成URL,并且您已经在其中传递了状态URL,这是错误的。

expect(
$state.href('details', { 
companyId: 'test-company' 
})
).toEqual('#/accounts/company/test-company')

我发现您对此功能进行单元测试的方法有问题,而应该以不同的方式对其进行测试。就像您应该首先从测试用例调用底层方法并检查您是否获得所需的结果一样。

控制器

function redirect() {
if (!$stateParams.companyId) {
$scope.promise = $state.go('home');
} else {
// get company details
}
}
$scope.redirect = redirect;

规格.js

//test pseudo code
describe('should redirect correctly', function(){
it('should redirect to details page when companyId is passed', function(){
//arrange
//TODO: please make sure, you avail useful dependency before using them  
var $scope = $rootScope.$new(),
mockParams = { companyId: 1 }
$controller('myCtrl', {$scope: $scope, $stateParams: mockParams });
//assert
$scope.redirect();
//act
$scope.$apply(); //apply the changes
expect($state.current.url).toEqual('#/accounts/company/test-company');
})
})

相关内容

最新更新