[英]Jasmine testing AngularJS $on
I want to test my typescript angular code with jasmine, but I get this error when I'm running it.我想用 jasmine 测试我的 typescript angular 代码,但是当我运行它时出现这个错误。
TypeError: 'undefined' is not an object (evaluating 'scope.LessonCtrl.statistic')
类型错误:'undefined' 不是一个对象(评估 'scope.LessonCtrl.statistic')
I'm trying to test this code:我正在尝试测试此代码:
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);
});
}
}
With this:有了这个:
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
});
Can anyone help me with this?谁能帮我这个?
You assign statistic
to the context ( this
), not scope.LessonCtrl
.您将
statistic
分配给上下文 ( this
),而不是scope.LessonCtrl
。 By using an arrow function the context will be preserved inside the .$on
callback通过使用箭头函数,上下文将保留在
.$on
回调中
Arrow functions capture the this value of the enclosing context...
箭头函数捕获封闭上下文的 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);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.