Unit testing AngularJS单元测试$location
我对单元测试和AngularJS非常陌生,我有一些无法解决的问题。我的一个测试不起作用。我试图通过影响一个值在测试中启动location.path(),但在我的控制器中,location.path()仍然有一个未定义的值 这是我的控制器:Unit testing AngularJS单元测试$location,unit-testing,angularjs,location,Unit Testing,Angularjs,Location,我对单元测试和AngularJS非常陌生,我有一些无法解决的问题。我的一个测试不起作用。我试图通过影响一个值在测试中启动location.path(),但在我的控制器中,location.path()仍然有一个未定义的值 这是我的控制器: angular.module('...') .controller('SignUpCtrl', ['$location', function ($location) { // Retrieve type of user var userTyp
angular.module('...')
.controller('SignUpCtrl', ['$location', function ($location) {
// Retrieve type of user
var userType = $location.path().substr(9);
if(userType == 'member'){
userType = 'user';
}
console.log($location.path());
console.log(userType);
$scope.uType = userType; ]);
这是我的测试模块:
describe('Controller: SignUpCtrl', function () {
// load the controller's module
beforeEach(module('...'));
var SignUpCtrl,
scope,
mockBackend,
environments,
location,
store;
beforeEach(inject(function ($controller, $rootScope, $httpBackend,$location,_Environments_) {
environments = _Environments_;
mockBackend = $httpBackend;
location = $location;
scope = $rootScope.$new();
SignUpCtrl = $controller('SignUpCtrl', {
$scope: scope,
$location: location
});
}));
it('should come from the right location', function(){
location.path('/sign-up/member');
expect(location.path()).toBe('/sign-up/member');
expect(scope.uType).toBe('user'); //Do not work
});
})) 您正试图使用单元测试来做一些只有使用端到端(或E2E)测试才能真正实现的事情。AngularJS中的单元测试旨在测试给定模块或子模块(例如
服务
、工厂
、指令
)中的javascript。然而,诸如页面导航或浏览器位置之类的东西确实需要在端到端测试环境中进行测试
因此,$location对象不会具有所有常规方法(如path
,url
,等等)。$location对象最终只是模块中实际$location对象的“模拟”。因此,您只需要将it('should from right location',function(){…})
的测试用例移动到端到端测试,然后继续进行其他特定于模块的单元测试。完成此操作后,只需抓取$scope
变量即可简化$controller,如下所示:
scope = $rootScope.new();
SignUpCtrl = $controller('SignUpCtrl', {$scope: scope});
E2E测试指南见。它将指导您如何编写好的E2E测试。有一个非常好的框架可以用来做角度E2E测试,称为量角器。有关这方面的信息,请访问。量角器将很快(在1.2中)取代Karma,成为处理E2E测试的更好方法。谢谢您的回复,我将看一看E2E测试,因为在单元测试中测试什么和E2E中测试什么对我来说仍然很困惑。。。