[Vuejs]-Node/vue.js unit test with a promise , how to write it correctly?

0👍

As @Bergi mentioned, the returned object should be a promise , so the correct test is :

      describe('loginUser', () => {
        var sandbox, payload, response
        beforeEach(() => {
          sandbox = sinon.sandbox.create()
        })
        afterEach(() => {
          sandbox.restore()
        })

        it('should return successful login', () => {
          payload = {user: {email: 'john.doe@domain.com', password: 'john123'}, requestOptions: {}}
          response = {data: {id: 1, name: 'John Doe', email: 'john.doe@domain.com', created_at: '2017-11-02T07:56:36.405Z', token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjMiLCJuYW1lIjoiSm9obiBMb2dpbiBEb2UiLCJhZG1pbiI6dHJ1ZX0.VHK2sCbj5nKJ8oC44UTHuhQHXEdPN8zjKjaFT0OZ-L'}}
          sandbox.stub(vueAuthInstance, 'login').withArgs(payload.user, payload.requestOptions).returns(Promise.resolve(response))

          return actions.login(store, payload)
          .then((result) => {
            expect(result).to.eql(true)
            expect(store.commit).to.have.been.calledWith(types.IS_AUTHENTICATED, { isAuthenticated: true })
            expect(store.commit).to.have.been.calledWith(types.CURRENT_USER_ID, { currentUserId: response.data.id })
          })
        })
       it('should return invalid login', () => {
          payload = {user: {email: 'john.doe@domain.com', password: 'john999'}, requestOptions: {}}
          response = {data: {}}
          sandbox.stub(vueAuthInstance, 'login').withArgs(payload.user, payload.requestOptions).returns(Promise.resolve(response))

          return actions.login(store, payload)
          .then((result) => {
            expect(result).to.eql(false)
            expect(store.commit).to.have.been.calledWith(types.IS_AUTHENTICATED, { isAuthenticated: false })
            expect(store.commit).to.have.been.calledWith(types.CURRENT_USER_ID, { currentUserId: '' })
          })
        })
      })

Leave a comment