我试图为Vue的mounted()
生命周期钩子中的逻辑编写一个单元测试,但运气不太好.问题似乎是,当使用vue test utils mount
安装组件时,永远不会调用mounted()
.下面是我要测试的Vue组件:
<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,那么这就失败了.
如果我用actions.logout()
个测试通过直接调用模拟的store操作,我还有其他一些测试也会调用store操作,比如按下按钮,这些操作也会通过,所以问题显然出在挂载的()生命周期钩子上.
有什么 idea 吗?
(vue 2.5.4
和vue测试utils 1.0.0-beta-.15
)