In a Vuex store action, I'm using this.app.router and a Nuxt plugin that injects the property $alert.

When I'm trying to test the Vuex store with Jest the test keeps failing because both of the properties are undefined.

I'm unit testing the getters, mutations, and actions separately as a javascript function like described here.

So not using Vue Test Utils or Vuex.

What I've already tried without any effect:

  • setup a new Vuex.Store and localVue from vue-test-utils.
  • setting a global variable with properties app and $alert before the test.
// actions.js
export default {
  async signup({ dispatch, state }, payload) {
      try {
        await dispatch('createUserData', payload)
        await dispatch('setUser', payload)
        this.app.router.push(state.redirectAfterLogin)
      } catch (error) {
        this.$alert.error(`errors.${error.code}`)
      }
  }
}

// actions.spec.js
import actions from '@/store/auth/actions'

describe('Auth store', () => {
  let dispatch
  let state

  test('signup', async () => {
    dispatch = jest.fn()
    state = {
      user: null
    }
    await actions.signup(
      { dispatch, state },
      {
        email: '[email protected]',
        password: 'password',
        displayName: 'Test'
      }
    )
    expect(dispatch).toHaveBeenCalledWith('createUserData')
    expect(dispatch).toHaveBeenCalledWith('setUser')
  })
})

Someone has any idea where and how I can define this method as mock functions in my test file?

0 Answers