代码之家  ›  专栏  ›  技术社区  ›  cmasri

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

  •  16
  • cmasri  · 技术社区  · 7 年前

    我正在尝试为Vue中的逻辑编写一个单元测试 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() 断言为false。

    如果我直接用 actions.logout() 测试通过了,我还有其他测试,这些测试也调用了按钮按下之类的存储操作,这些测试也通过了,所以问题显然是mounted()生命周期挂钩的问题。

    有什么想法吗?

    (vue 2.5.4 和vue测试UTIL 1.0.0-beta-.15 )

    2 回复  |  直到 6 年前
        1
  •  8
  •   Yun    3 年前

    不知道这有什么不同,但我将商店模拟抽象为另一个文件,现在一切似乎都正常了。

    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()
      })
    })
    
        2
  •  1
  •   Daniel Danielecki    4 年前

    无需将存储模拟抽象为另一个文件,也无需 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();
      });
    });