【问题标题】:How to access this.app and/or a injected plugin in a Vuex store test with Nuxt and Jest如何使用 Nuxt 和 Jest 在 Vuex 商店测试中访问 this.app 和/或注入插件
【发布时间】:2019-09-20 19:37:35
【问题描述】:

在 Vuex 存储操作中,我使用 this.app.router 和注入属性 $alert 的 Nuxt 插件。

当我尝试使用 Jest 测试 Vuex 商店时,测试一直失败,因为这两个属性都未定义。

我将 getter、mutations 和 action 分别作为一个 javascript 函数进行单元测试,如 here 所述。

所以不要使用 Vue Test Utils 或 Vuex。

我已经尝试过的没有任何效果:

  • vue-test-utils 设置一个新的Vuex.StorelocalVue。
  • 在测试前使用属性 app 和 $alert 设置全局变量。
// 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: 'test@test.nl',
        password: 'password',
        displayName: 'Test'
      }
    )
    expect(dispatch).toHaveBeenCalledWith('createUserData')
    expect(dispatch).toHaveBeenCalledWith('setUser')
  })
})

有人知道我可以在哪里以及如何在我的测试文件中将此方法定义为模拟函数?

【问题讨论】:

  • 同样的问题 - 你找到解决办法了吗?

标签: vue.js jestjs vuex nuxt.js


【解决方案1】:

当您单独测试它们时,非常简单的操作是纯函数 在await actions.signup 之前添加: actions.$alert ={}; actions.$alert.error =jest.fn(); 或者甚至更好地将它添加到 beforeEach 函数中

【讨论】:

    【解决方案2】:
    1. 在 Vuex 中使用 localVue
    2. 模拟$alert Vuex.Store.prototype.$alert = jest.fn().mockReturnValue({})

    【讨论】:

      猜你喜欢
      • 2018-12-19
      • 2020-12-07
      • 2020-01-29
      • 2020-08-25
      • 2021-07-22
      • 2018-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多