【问题标题】:Jasmine testing AngularJS $onJasmine 测试 AngularJS $on
【发布时间】:2016-02-14 12:37:20
【问题描述】:

我想用 jasmine 测试我的 typescript angular 代码,但在运行它时出现此错误。

TypeError: 'undefined' 不是对象(评估 'scope.LessonCtrl.statistic')

我正在尝试测试这段代码:

export class LessonCtrl {
  scope: angular.IScope;
  statistic: Statistic;

  constructor($scope) {
    this.scope = $scope;
    this.statistic = new Statistic();
    this.scope.$on("timer-stopped", function(event, data) {
      var scope: any = event.currentScope;
      scope.LessonCtrl.statistic.calculateTypingSpeed(data.millis);
      scope.LessonCtrl.statistic.setTime(data.millis);
    });
  }
}

有了这个:

var scope, rootScope, lessonCtrl;

beforeEach(() => inject(($rootScope) => {
  scope = $rootScope.$new();
  rootScope = $rootScope;
  lessonCtrl = new Controllers.LessonCtrl(scope);
}));

it('on test', () => {
  rootScope.$broadcast('timer-stopped', [{millis: 1000}]);   
  expect(true).toBe(true); // i will expect something else but i have errors
});

谁能帮我解决这个问题?

【问题讨论】:

    标签: javascript angularjs typescript jasmine


    【解决方案1】:

    您将 statistic 分配给上下文 (this),而不是 scope.LessonCtrl。通过使用arrow function the context will be preserved inside the .$on callback

    箭头函数捕获封闭上下文的 this 值...

    export class LessonCtrl {
      scope: angular.IScope;
      statistic: Statistic;
    
      constructor($scope) {
        this.scope = $scope;
        this.statistic = new Statistic();
        this.scope.$on("timer-stopped", (event, data) => {
          var scope: any = event.currentScope;
          this.statistic.calculateTypingSpeed(data.millis);
          this.statistic.setTime(data.millis);
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 2014-05-04
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多