How to test $q promises in angularJs with mocha, chai, sinon -
we have moved mocha, chai , sinon our test libraries , coming jasmine little confused how test promises.
i have form submit function calls service , on return navigates user correct state:
submit(event, theform){ event.preventdefault(); if(theform.$valid){ this.authenticationservice.authenticateuser({ email: this.email, password: this.password }).then( (result) => { this.$state.go('dashboard.home') }); } }
have gotten part of way there following test:
it('should submit login credentials if valid', function(){ var dfd = q.defer(), promise = dfd.promise; controller.email = 'ryan.pays@leotech.com.sg'; controller.password = 'password123'; sinon.stub(service, 'authenticateuser').returns(promise); sinon.spy(state, 'go'); sinon.spy(controller, 'submit'); controller.submit(event, theform); dfd.resolve(); expect(controller.submit).to.have.been.called; expect(controller.submit).to.have.been.calledwith(event, theform); expect(event.preventdefault).to.have.been.called; expect(service.authenticateuser).to.have.been.called; expect(service.authenticateuser).to.have.been.calledwith({ email: controller.email, password: controller.password }); expect(state.go).to.have.been.called; expect(state.go).to.have.been.calledwith('dashboard.home'); });
but assertion state.go
called not pass. change test make pass?
likely timing issue in expect()
's being called before then()
in controller has executed. correct this, try wrapping state.go
assertions in finally()
so:
it('should submit login credentials if valid', function(){ [...] return promise.finally(function() { expect(state.go).to.have.been.called; expect(state.go).to.have.been.calledwith('dashboard.home'); ); });
two important things happening here:
finally()
ensuresexpect()
's not run untildfd
has been resolved.finally()
returns promise returning mocha test itself. tells mocha dealing asynchronous code , prevents moving on further tests untilexpect()
's have executed. can read more handling asynchronous code in mocha here.
Comments
Post a Comment