Reputation: 107
I need to write a test that sets state then test to see if stateManagerService has been called. I'm getting the error:
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');
}
}
}
unit test 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();
});
Also (slightly off-topic) I'm still confused as to why this.$state = $state is required. If left out, I get an error saying $state is undefined.
Update: Now getting the errors
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})
}
}
Upvotes: 0
Views: 2908
Reputation: 1051
You need to verify on the function pointer, not the return value of the function.
It should have been
expect(vm.stateManagerService.go).toHaveBeenCalled();
Note the absence of ()
around the go
Upvotes: 1