15

我正在尝试为 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(),并且我还有其他测试也调用存储操作,例如按下按钮,并且这些操作也通过了,所以问题肯定出现在 mount() 生命周期钩子上.

有什么想法吗?

(vue2.5.4和 vue-test-utils 1.0.0-beta-.15)

4

2 回答 2

8

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()
  })
})
于 2018-07-10T16:18:29.433 回答
1

没有将商店模拟抽象到另一个文件,并且没有beforeEach(由于某种原因破坏了我的测试)的方法略有不同。

import { createLocalVue, shallowMount } from "@vue/test-utils";
import Vuex from "vuex";
import MyComponent from "@/components/MyComponent.vue";

describe("MyComponent", () => {
  const localVue = createLocalVue();
  localVue.use(Vuex);

  const actions = {
    logout: jest.fn()
  };
  const store = new Vuex.Store({ actions });

  const wrapper = shallowMount(MyComponent, {
    localVue,
    store
  });

  it('calls store "logout" action', () => {
    expect(actions.logout).toHaveBeenCalled();
  });
});
于 2021-04-07T14:13:42.523 回答