我正在尝试为 Vue 中的逻辑编写一个单元测试mounted()
生命周期钩子,但运气不太好。问题似乎是这样的mounted()
使用 vue-test-utils 安装组件时永远不会被调用mount
。这是我要测试的 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()
断言为假。
如果我直接调用模拟商店操作actions.logout()
测试通过了,我还有其他测试,这些测试也对按下按钮之类的事情调用存储操作,并且这些测试也通过了,所以问题肯定出在 Mounted() 生命周期挂钩上。
有什么想法吗?
(vue 2.5.4
和 vue-test-utils1.0.0-beta-.15
)
不确定它有什么不同,但我将商店模拟抽象到另一个文件,现在一切似乎都正常。
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()
})
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)