在 Vuex + Jest 中,如何对正在调用商店的 getter 进行单元测试?

In Vuex + Jest, how to unit test a getter which is calling the store?

我正在尝试从我的 vuex 商店中测试以下非常简单的 getter。它只是连接两个字符串:

const getters = {
  adressToGet: state => {
    return state.baseAdress + store.getters.queryToGet
  }
 }

模拟状态部分很容易,但我找不到模拟商店的好方法。

如果这是在组件中,我可以使用 mountshallow 挂载组件并为其分配模拟商店,但事实并非如此。这是来自 vuex 商店。

这是我的测试代码:

import Search from '@/store/modules/search'

jest.mock('@/store/modules/search.js')

describe('search.js', () => {

  test('The adress getter gets the right adress', () => {
    const state = {
      baseAdress: 'http://foobar.com/'
    }
    // I define store here, but how can I inject it into my tested getter ?
    const store = { 
      getters: {
        queryToGet: 'barfoo'
      }
    }
    expect(Search.getters.adressToGet(state)).toBe('http://foobar.com/barfoo')
  })
})

我得到 http://foobar.com/undefined 而不是预期的结果。

执行此操作的最佳方法是什么?

编辑:按照第一条评论,我的新版本,但它仍然给出相同的结果:

import Search from '@/store/modules/search'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'

jest.mock('@/store/modules/search.js')

describe('search.js', () => {

  test('The adress getter gets the right adress', () => {
    const localVue = createLocalVue()
    localVue.use(Vuex)

    const mockState = {
      baseAdress: 'http://foobar.com/'
    }

    const store = new Vuex.Store({
      state: mockState,
      getters: {
        queryToGet: function () {
          return 'barfoo'
        }
      }
    }) 

   expect(Search.getters.adressToGet(mockState))
   .toBe('http://foobar.com/barfoo')
  })
})

经过大量研究,我意识到我必须用 Jest 来模拟商店依赖。这似乎是完成并通过测试的正确方法:

import Search from '@/store/modules/search'

jest.mock('@/store/index.js', () =>({
  getters: {
    queryToGet: 'barfoo'
  }
}))

jest.mock('@/store/modules/search.js')

describe('search.js', () => {
  test('The adress getter gets the right adress', () => {
    const state = {
      baseAdress: 'http://foobar.com/'
    }
    expect(Search.getters.adressToGet(state))
    .toBe('http://foobar.com/barfoo')
  })
})