2013-10-13 101 views
2

我是单元测试和AngularJS的新手,我有一些问题我无法解决。我的一个测试不起作用。我试图通过影响一个值在我的测试中启动location.path(),但在我的控制器中,location.path()仍然有一个未定义的值。

这里是我的CONTROLER:

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

});

回答

2

您正在尝试使用单元测试来做一些只能使用端到端(或E2E)测试才能实现的功能。 AngularJS中的单元测试旨在测试给定模块或子模块内的javascript(例如service,factory,directive等)。但是,页面导航或浏览器位置等事情确实需要在端到端测试环境中进行测试。

因此,您的$ location对象将不具有所有常规方法(如pathurl等)。 $ location对象最终只是作为您在模块中获得的实际$ location对象的“模拟”而已。因此,您只需将您的测试用例it('should come from the right location', function(){ ... })移动到端到端测试,然后继续进行其他模块特定的单元测试。当你这样做,你可以只抓住了$scope变量,如下面的简化$控制器:

scope = $rootScope.new(); 
SignUpCtrl = $controller('SignUpCtrl', {$scope: scope}); 

的端到端测试的指南可以在this link找到。它引导您了解如何编写良好的E2E测试。有一个非常好的框架可用于角度E2E测试,称为量角器。该信息在this link。量角器很快将在1.2版本中取代Karma作为处理E2E测试的更好方法。

+0

感谢您的回应我会看看E2E测试,因为它仍然让我非常困惑在单元测试中测试什么以及E2E中的什么... – user2876974