[英]Jasmine testing AngularJS $on
我想用 jasmine 測試我的 typescript angular 代碼,但是當我運行它時出現這個錯誤。
類型錯誤:'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
});
誰能幫我這個?
您將statistic
分配給上下文 ( this
),而不是scope.LessonCtrl
。 通過使用箭頭函數,上下文將保留在.$on
回調中
箭頭函數捕獲封閉上下文的 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.