如何使用 Nuxt 和 Jest 在 Vuex 商店测试中访问 this.app 和/或注入插件

Posted

技术标签:

【中文标题】如何使用 Nuxt 和 Jest 在 Vuex 商店测试中访问 this.app 和/或注入插件【英文标题】:How to access this.app and/or a injected plugin in a Vuex store test with Nuxt and Jest 【发布时间】: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')
  )
)

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

【问题讨论】:

同样的问题 - 你找到解决办法了吗? 【参考方案1】:

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

【讨论】:

【参考方案2】:
    在 Vuex 中使用 localVue 模拟$alert Vuex.Store.prototype.$alert = jest.fn().mockReturnValue()

【讨论】:

以上是关于如何使用 Nuxt 和 Jest 在 Vuex 商店测试中访问 this.app 和/或注入插件的主要内容,如果未能解决你的问题,请参考以下文章