Vue检查动作是否使用spyOn调用其他动作

nic*_*nck 2 vue.js jestjs spyon

在Vue中,我想检查商店中的某个动作是否正确地使用Jest's调用了另一个动作spyOn,我以不同的方式尝试了它,但是它似乎不起作用,这是我的代码:

// index.js

getRecipes ({ dispatch }) {
  const fruits = ['apple', 'banana', 'pear']
  fruits.forEach((fruit) => {
    dispatch('getRecipe', fruit)
  })
},
async getRecipe ({ commit }) {
  const recipe = await recipesService.fetchRecipe(payload)

  commit(SET_RECIPE, { recipe })
},
Run Code Online (Sandbox Code Playgroud)

// index.spec.js

test('getRecipes calls getRecipe 3 times, each with the right fruit', () => {
  const commit = jest.fn()
  const dispatch = jest.fn()
  const spy = spyOn(actions, 'getRecipe')
  const result = actions.getRecipes({ commit, dispatch })

  expect(spy).toHaveBeenCalledTimes(3)
  expect(spy).toHaveBeenCalledWith('apple')
})
Run Code Online (Sandbox Code Playgroud)

但是当我运行测试时,这是我得到的输出:

Expected spy to have been called three times, but it was called zero times.
Run Code Online (Sandbox Code Playgroud)

我在其他地方想测试这些集成(一个动作调用另一个),但是它仍然给我这个错误。

Ser*_*eon 5

仅测试您的代码,而不测试vuex

这种测试的问题在于,您正在测试vuex是否按预期工作,这可能毫无价值。

而不是直接监视actions,并断言vuex getRecipedispatch('getRecipe', fruit)被调用时正确地调用了该动作,我将测试该getRecipes动作dispatch是否正确调用:

test('getRecipes dispatches 3 "getRecipe" actions, each with the right fruit', () => {
  const commit = jest.fn()
  const dispatch = jest.fn()
  const result = actions.getRecipes({ commit, dispatch })

  expect(dispatch).toHaveBeenCalledTimes(3)
  expect(dispatch.mock.calls[0][0]).toBe('apple')
  expect(dispatch.mock.calls[1][0]).toBe('banana')
  expect(dispatch.mock.calls[2][0]).toBe('pear')
})
Run Code Online (Sandbox Code Playgroud)

如果您仍然想测试vuex集成怎么办

您并没有真正显示出如何导入和导出模块,但是我想在您的代码中,操作文件仅导出具有操作的普通对象,而测试仅将其导入。

在您的应用程序代码中,可能是您正在将这些操作添加到vuex,然后使用以下命令将vuex加载到您的应用程序中:

new Vue({store})
Run Code Online (Sandbox Code Playgroud)

因此,在您的测试中,该actions模块实际上对vuex本身一无所知(在这里,我猜是真的,无法从您已发布的代码中真正看出来,但这很有可能)。

这就是为什么您的测试无法按预期方式工作的原因,因为在测试中该getRecipes方法只是获取一个dispatch参数并调用了它,但是vuex并没有真正在该处执行任何操作,因此该dispatch调用无法调用另一个动作。

现在,如果您仍然想通过玩笑来进行测试,则应该从组件执行此操作,以便在vue和vuex的上下文中测试动作。

在vue test utils文档中有一个很好的教程。