vue-test-utils:如何测试Mounted()生命周期挂钩中的逻辑(使用vuex)?

cma*_*sri 6 unit-testing vue.js jestjs vuex vue-test-utils

我正在尝试为Vue的mounted()生命周期挂钩中的逻辑编写单元测试,但运气不佳。问题似乎mounted()是使用vue-test-utils挂载组件时从未调用过mount。这是我要测试的Vue组件:

<template>
  <div></div>
</template>

<script>   
export default {
  name: 'MyComponent',
  mounted () {
    this.$store.dispatch('logout')
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

测试本身:

import { mount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import MyComponent from '@/components/MyComponent'

const localVue = createLocalVue()

localVue.use(Vuex)

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

  beforeEach(() => {
    actions = {
      logout: jest.fn().mockName('logout')
    }
    store = new Vuex.Store({
      state: {},
      actions
    })
  })

  it('calls store "logout" action', () => {
    mount(MyComponent, { localVue, store })
    expect(actions.logout).toHaveBeenCalled()
  })
})
Run Code Online (Sandbox Code Playgroud)

但是,这失败并expect(logout).toHaveBeenCalled()断言为false。

如果我actions.logout()通过测试通过直接调用模拟的存储操作,并且我还有其他测试也对诸如按钮按下之类的东西调用存储操作,并且这些测试也通过了,那么问题肯定出在mount()生命周期挂钩上。

有什么想法吗?

(vue 2.5.4和vue-test-utils 1.0.0-beta-.15

cma*_*sri 8

不知道有什么不同,但我将商店模拟抽象到另一个文件,现在一切似乎都可以正常工作。

mocks.js

export const storeMock = Object.freeze({
  state: {},
  actions: {
    logout: jest.fn().mockName('logout')
  },
})
Run Code Online (Sandbox Code Playgroud)

test.spec.js

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import { storeMock } from './mocks.js' 
import MyComponent from '@/components/MyComponent'

const localVue = createLocalVue()

localVue.use(Vuex)

describe('MyComponent.vue', () => {
  let options

  beforeEach(() => {
    jest.clearAllMocks()
    const store = new Vuex.Store(storeMock)
    options = { store, localVue }
  })

  it('calls store "logout" action', () => {
    shallowMount(MyComponent, options)
    expect(storeMock.actions.logout).toHaveBeenCalled()
  })
})
Run Code Online (Sandbox Code Playgroud)