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

问题描述:

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

I'm trying to write a unit test for the logic within Vue's mounted() lifecycle hook, but not having much luck. The problem seems to be that mounted() never gets called when the component is mounted using vue-test-utils mount. Here's the Vue component I'm trying to test:

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

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

测试本身:

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

但是,此操作失败,因为 expect(logout).toHaveBeenCalled()声明为false.

However, this fails with expect(logout).toHaveBeenCalled() asserting false.

如果我直接使用 actions.logout()调用模拟的存储操作,则测试通过,而我还有其他测试,这些测试也调用了诸如按下按钮之类的存储操作,这些也通过了,因此问题肯定出在Mounted()生命周期挂钩上.

If I call the mocked store action directly with actions.logout() the test passes, and I have other tests which also call store actions on things like a button press, and those pass as well, so the problem definitely appears to be with the mounted() lifecycle hook.

有什么想法吗?

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

(vue 2.5.4 and vue-test-utils 1.0.0-beta-.15)

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

Not sure how it's any different, but I abstracted the store mock to another file and everything seems to work now.

mocks.js

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

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