angularjs - how to properly use toHaveBeenCalled() for unit testing? -
i need write test sets state test see if statemanagerservice has been called. i'm getting error:
undefined not 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 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 why this.$state = $state required. if left out, error saying $state undefined.
update: getting errors
error: spyon not find object spy upon go() (line 1887)
typeerror: undefined not 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 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}) } }
you need verify on function pointer, not return value of function.
it should have been
expect(vm.statemanagerservice.go).tohavebeencalled();
note absence of ()
around go
Comments
Post a Comment