2015-09-01 76 views
2

我正在用AngularJs 1.4.4编写一个应用程序,并且刚刚开始使用TDD。我在Jasmine中使用Karma,并且没有在$ scope上测试表达式的麻烦,但是当试图在Controller中测试使用'this'定义的表达式时,它将返回为undefined。 Angular表示在你的控制器中使用'this'是最好的练习,但我还没有找到一个明确的测试例子。AngularJs单元测试'这''

这里是我的控制器

'user_strict'; 
 
var app = angular.module('app', ['ngRoute', 'ngAnimate']); 
 

 
angular.module('app') 
 
app.controller('LoginCtrl', ['$scope', function($scope) { 
 

 
    var login = this; 
 
    
 
    login.user = {message:'hello'}; 
 
    
 
    $scope.userName = "Anthony"; 
 
    
 
    }])

我的测试脚本

'use strict'; 
 

 
describe('Controller: LoginCtrl', function() { 
 
\t 
 
\t // load the controller's module 
 
\t beforeEach(module('app')); 
 

 
\t var LoginCtrl, 
 
\t scope; 
 

 
\t // initalize the controller and a mock scope 
 
\t beforeEach(inject(function ($controller, $rootScope) { 
 
\t \t scope = $rootScope.$new(); 
 
\t \t LoginCtrl = $controller('LoginCtrl', { 
 
\t \t \t $scope: scope, 
 
\t \t }); 
 

 
\t })); 
 

 
\t it('should equal to equal to Anthony', function() { 
 
\t \t expect(scope.userName).toBe("Anthony"); 
 
\t }); 
 

 
\t it('login user should equal to hello', function() { 
 
\t \t expect(login.user.message).toBe('hello'); 
 
\t }) 
 
});

第一个测试通过,但塞康d返回这个错误/失败;

控制器:LoginCtrl登录用户应该等于为hello FAILED

类型错误: '未定义' 不是(评价 'login.user.message')的对象

我的假设是,它需要像控制器和范围注入,但我试过的方法没有奏效。任何帮助非常感谢:)

回答

1
var login = this; 

在JavaScript变量的本地功能scope.They不可访问的功能。

你正在尝试做同样的事情。那么你得到TypeError undefined

这样做。

$scope.login = this; 

$scope.login.user = {message:'hello'}; 

login后,可通过$scope

+0

谢谢,完美的作品!但是AngularJs的例子没有显示这一点。你有什么想法,为什么? –

+0

哪个AngularJs例子?没有得到问题。 –

+0

查看本页面上的控制器和范围部分; https://google-styleguide.googlecode.com/svn/trunk/angularjs-google-style.html –

2

使用this在控制器是所谓“控制器”图案,其在official docs简要描述。

考虑以下代码:

app.controller('LoginCtrl', ['$scope', function($scope) { 
    var login = this; 
    login.user = {message:'hello'}; 
    $scope.userName = "Anthony"; 
}]); 

这里,function ($scope) { ... }是你控制器和this构造对象引用,这将执行构造函数时创建的内部构造。这个对象将包含你使用this分配给它的所有内容。当您在代码中创建控制器代码

LoginCtrl = $controller('LoginCtrl', { $scope: scope }); 

变量LoginCtrl认为,构造的对象。您可以通过LoginCtrl变量引用它的属性,分配为this。所以基本上你的测试应该改为:

it('login user should equal to hello', function() { 
    expect(LoginCtrl.user.message).toBe('hello'); 
}) 

积分到Q/A accessing $scope from unit test file when using the vm "ControllerAs" syntax from AngularJS HotTowel,在那里你可以找到更多信息。