【问题标题】:Can we modify Vuex action for jest unit testing?我们可以修改 Vuex 操作以进行开玩笑的单元测试吗?
【发布时间】:2019-09-26 09:06:07
【问题描述】:

我在我的测试文件中创建了一个商店

import {
shallowMount,
createLocalVue
} from '@vue/test-utils'
import Vuex from 'vuex'
import Actions from '../../../src/components/Actions'

const localVue = createLocalVue()

localVue.use(Vuex)

describe('Actions.vue', () => {
  let actions
  let store

beforeEach(() => {
    actions = {
        actionClick: jest.fn(() => Promise.resolve({}))
    }
    store = new Vuex.Store({
        actions
    })
})

it('should go to then block', () => {
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //goes to then block
})

it('should go to catch block', () => {
    actions.actionClick = jest.fn(() => Promise.reject(new Error()))
    const wrapper = shallowMount(Actions, {
        store,
        localVue
    })
    //still goes to then block and not the catch block
  })
})

根据上面的代码,我无法实现第二个测试块意味着它没有修改存储中的 actionClick 函数。

【问题讨论】:

    标签: vue.js vuejs2 jestjs vuex vue-test-utils


    【解决方案1】:

    beforeEach 钩子发生在它进入it 块之前。所以store的设置此时实际上已经完成。据我从vuex 源代码中可以看到,它将操作回调与您在创建步骤(store = new Vuex.Store(...))传递给它的选项对象分离。您可以查看here

    所以,我建议您在 it 块内创建新的商店对象:

    it('should go to catch block', () => {
        actions.actionClick = jest.fn(() => Promise.reject(new Error()))
        store = new Vuex.Store({ actions })
        const wrapper = shallowMount(Actions, {
            store,
            localVue
        })
        //still goes to then block and not the catch block
      })
    })
    

    或者在 store 实例上使用 hotUpdate (newOptions) 方法。我没有测试这个。但是,同样,从 vuex source 它应该完全满足您的需求。

    it('should go to catch block', () => {
        actions.actionClick = jest.fn(() => Promise.reject(new Error()))
        store.hotUpdate({ actions })
        const wrapper = shallowMount(Actions, {
            store,
            localVue
        })
        //still goes to then block and not the catch block
      })
    })
    

    【讨论】:

    • hotUpdate() 工作了!谢谢!有文件吗?
    • @aniket_777 在他们的 API 和热重载部分。这是参考 -> vuex.vuejs.org/api/#hotupdate
    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多