2016-04-22 29 views
0

我需要編寫一個測試,設置狀態然後測試以查看stateManagerService已被調用。我發現了錯誤:如何正確使用toHaveBeenCalled()進行單元測試?

undefined is not an object (evaluating 'vm.stateManagerService.go')

main.controller.js

export class MainController { 
    constructor($state, stateManagerService) { 
     'ngInject'; 
     this.$state = $state; 
     if($state.current.name === 'main') { 
      stateManagerService.go('list'); 
     } 
    } 

} 

單元測試main.controller.spec.js

describe('controllers',() => { 
    let vm; 

    // 
    beforeEach(inject(($controller, $state, stateManagerService) => { 
     vm = $controller('MainController'); 

    })); 

    it('should call stateManagerService when current name is main',()=> { 
     vm.$state.current.name = 'main' 
     console.log(vm.$state.current.name) 
     expect(vm.stateManagerService.go()).toHaveBeenCalled(); 
    }); 

而且(略題外話)我仍然困惑爲什麼這個。$ state = $狀態是必需的。如果省略,我得到一個錯誤,說$狀態是未定義的。

更新:現在得到的錯誤

Error: spyOn could not find an object to spy upon for go() (line 1887)

TypeError: undefined is not an object (evaluating 'vm.stateManagerService.go')

stateManager.service.js

export class StateManagerService { 
    constructor($state, $stateParams, platformDetectService){ 
     'ngInject'; 
     //deps 
     this.$state = $state; 
     this.$stateParams = $stateParams; 
     this.isMobile = platformDetectService.isMobile; 

     //internal 
     this.lastStateName = null; 
     this.lastStateParams = null; 
    } 

    //storage method for current state 
    go (stateName, params){ 
     this.lastStateParams = this.$stateParams.page; 
     this.lastState = this.$state.current.name.split('.')[1]; 



     let nextState = (this.isMobile) ? 'mobile.' + stateName : 'map.' + stateName; 

     this.$state.go(nextState, params) 
    } 

    //returns last state or list 
    goBack(){ 
     let lastState = this.lastState || 'list', 
      page = this.lastStateParams || null; 

     this.go(lastState, {page}) 
    } 

} 
+0

不要忘記窺視你的'vm.stateManagerService.go'通過'spyOn(vm.stateManagerService, '走出去' )' – kazupooot

+0

**間諜**和'.toHaveBeenCalled'的Jasmine文檔 - http://jasmine.github.io/2.0/introduction.html#section-Spies without method explicity invocation –

回答

1

您需要驗證函數指針,而不是函數的返回值。

應該已經

expect(vm.stateManagerService.go).toHaveBeenCalled(); 

注意沒有()圍繞go