测试失败并显示'this。$ store.dispatch is not function'-vue-test-utils

时间:2019-03-02 05:37:22

标签: vuex vue-test-utils

我将Jest与vue-test-utils结合使用来编写组件测试。我宣布存储为全局存储,并能够在其他测试中使用它来创建模拟。

但是只有该测试失败,并且'this。$ store.dispatch不是一个函数'。我检查了所有其他解决方案,但找不到解决方案。这是代码

nav-section.spec.js

  import NavSection from '@/components/NavSection';
  import render from '../../test-utils/render';

  describe('NavSection', () => {
    it('commits a mutation when the form is submitted', () => {
     const storeMock = {
     commit: jest.fn()  
    }

    const options = {
      propsData: {
        fixedNav: null,
        showNavSearch: true,
      },
      mocks: {
        $store: storeMock,
      },
    };

    const wrapper = render(NavSection, options);

    wrapper.find('.hero_search-form').trigger('submit');

    expect(storeMock.commit).toHaveBeenCalledWith(
      'SET_QUERY', 
      {query: { q: 'foo' }, shouldNavigate:true});
   });
  });

此NavSection.vue

<template>
 ...
</template>

<script>
import { FETCH_LISTS } from '@/store/action-types';
import { SET_QUERY } from '@/store/mutation-types';

export default {
  props: ['showNavSearch', 'fixedNav'],
  name: 'nav-section',
  data: () => ({ form: { searchTerm: '' } }),
  computed: {
    listsCount() {
      return this.$store.state.shareLists.length;
    },
  },
  mounted() {
    this.$store.dispatch(FETCH_LISTS);
  }
  methods: {
    onSubmit() {
      this.$store.commit(SET_QUERY, { query: { q:    this.form.searchTerm},shouldNavigate: true });
    },
  },
};
</script>

这是render.js

import Puex from 'puex';
import { shallowMount, createLocalVue } from '@vue/test-utils';
import sampleStore from '../sampleStore/';

const localVue = createLocalVue();
localVue.use(Puex);

const render = (Component, options = { localVue }) => {
  if (!options.store) {
    const store = new Puex(sampleStore);
    options.store = store;
  }

  return shallowMount(Component, options);
};

export default render;

0 个答案:

没有答案