AngularJs 单元测试 'this'

AngularJs unit test 'this'

我正在使用 AngularJs 1.4.4 编写一个应用程序,并且刚刚开始第一次使用 TDD。我将 Karma 与 Jasmine 一起使用,并且在 $scope 上测试表达式没有遇到任何问题,但是当尝试测试在控制器中使用 'this' 定义的表达式时,它 returns 未定义。 Angular 表示在控制器中使用 'this' 是最佳实践,但我还没有找到明确的测试示例。

这是我的控制器

'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() {
 
 // load the controller's module
 beforeEach(module('app'));

 var LoginCtrl,
 scope;

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

 }));

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

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

第一个测试通过,但第二个 return 这个 error/fail;

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

TypeError: 'undefined' 不是对象(正在计算 'login.user.message')

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

var login = this;

在 JavaScript 中,变量是函数的局部变量 scope.They 在函数外部不可访问。

您正在尝试以相同的方式 things.Thats 获得 TypeError undefined

照这样做。

$scope.login = this;

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

此后 login 可通过 $scope

获得

在控制器中使用 this 是所谓的 "controller as" 模式,在 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,您可以在其中找到更多信息。