2015-05-26 31 views
0

嘗試寫我的控制器單元測試:

app.controller('StartGameCtrl', function ($scope, $timeout,$state) { 
     $scope.startGame = function() { 
     $scope.snap = false; 
     $scope.dealCards(); 
     debugger; 
     $state.go('cpu'); 
     } 
    }); 

我寫這篇茉莉單元測試:

describe('snap tests', function() { 
    beforeEach(module('snapApp')); 
    var scope, createController, state; 

    beforeEach(inject(function ($rootScope, $controller,$state) { 
    scope = $rootScope.$new(); 
    createController = function() { 
     return $controller('StartGameCtrl', { 
     '$scope':scope, 
     '$state':state 
     }); 
    }; 
    })); 


    it('startGame should call dealcards', function() { 
    var controller = createController(); 
    spyOn(scope, 'dealCards'); 
    scope.startGame(); 
    //expect(scope.dealCards).toHaveBeenCalled(); 
    }); 

}); 

,當我跑我的人緣測試中,我得到一個錯誤:

TypeError: 'undefined' is not an object (evaluating '$state.go') 
at startgamectrl.js:9 
+0

貴'snapApp'模塊包含在裏面'ui.router'模塊? –

回答

1

您已將$state本地分配爲state(您的規範中未定義的變體),而不是注入的$state servi CE。

不是那樣做,我只是爲$state創建了一個間諜。例如...

beforeEach(inject(function ($rootScope, $controller) { 
    scope = $rootScope.$new(); 
    state = jasmine.createSpyObj('$state', ['go']); 
    createController = function() { 
     return $controller('StartGameCtrl', { 
      '$scope':scope, 
      '$state':state 
     }); 
    }; 
})); 

然後你就可以測試它被稱爲

expect(state.go).toHaveBeenCalledWith('cpu');