我试图为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)

推荐答案

我不确定这有什么不同,但我把store 模型抽象成了另一个文件,现在一切似乎都正常了.

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

Vue.js相关问答推荐

Vue Router中.getRoutes()获取的路由顺序优化建议

作为props 传递的原始 ref 的 Vue 3 react 性

Nuxt3-Vue中的useRoute和useRouter有什么区别

为什么我在 Vue npm run serve 的 localhost 中得到无法获取

如何在 vue 路由中导航到 Bootstrap-vue 选项卡中的特定选项卡?

在 Vue 中启用(控制台)记录路由事件

VueJS - 将单独的组件加载到 vue 实例中

如何对对象数组进行 v-model

避免在运行时向 Vue 实例或其根 $data 添加响应式属性

如何使用 Vue 命名插槽呈现静态内容列表?

从组件的 内的组件调用方法

重新加载发布到 Github 页面的 Vue 网站时出现 404

vue-router的router-link实际刷新?

Vue 组件 Vue-Instant

阻止 Vue 积极重用 dom 元素

在 .vue 文件中使用 Vue.set() 和 Vue.use()

如何将事件绑定到 Vuetify 中的树视图 node ?

try 通过 Vue.js 中的渲染传递props并观察它们

vuex - 即使不推荐,是否可以直接更改状态?

超过最大调用堆栈大小 Vuetify