2015-11-13 255 views
1

我想用茉莉花測試打字稿角碼,但是當我運行它時出現這個錯誤。

TypeError: 'undefined' is not an object (evaluating '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 
}); 

誰能幫助我?

回答

1

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

Arrow functions capture the this value of the enclosing context...

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); 
    }); 
    } 
} 
+0

感謝它解決我的問題! – bucicimaci