我们可以修改 Vuex 动作来进行 jest 单元测试吗?

Can we modify Vuex action for jest unit testing?

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

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 函数。

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
  })
})

或在商店实例上使用 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
  })
})