我想用茉莉花来测试我的打字稿角度代码,但是在运行它时出现此错误。
TypeError:“未定义”不是对象(正在评估“ 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
});
谁能帮我这个?
最佳答案
您将statistic
分配给上下文(this
),而不是scope.LessonCtrl
。通过使用arrow function the context will be preserved inside the .$on
callback
箭头函数捕获封闭上下文的此值。
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);
});
}
}