如何在Mocha单元测试中访问命名空间的Vuex getter

时间:2019-05-30 20:49:24

标签: unit-testing vue.js mocha vuex

我正在构建一个新的Vue组件,该组件使用命名空间的Vuex getter访问列名列表。实际的组件将编译并运行。

在我的Mocha单元测试中,我创建了一个模拟的吸气剂,该吸气剂返回一个称为“ allColumns”的字符串列表。当我运行单元测试时,在ShallowMount期间,组件的方法尝试在初始化期间访问this.allColumns,但该值始终未定义。我可以在this。$ store.getters.allColumns中看到所需的值,但是它没有像在浏览器中打开页面时那样映射到this.allColumns。

关于如何在测试中模拟getter以及如何在名称空间中使用mapGetters的信息很多,但是我没有在Mocha测试中找到有关命名空间getter的任何文档。

test.spec.js

  let propsData;
  let getters;
  let store;

  beforeEach(() => {
    debugger;
    propsData = {
      players: samplePlayerObject,
      metadata: sampleMetadataObject
    };

    getters = {
      allColumns: () => ["playerid","last","first","birthday","height"]
    }

    store = new Vuex.Store({
      getters
    });
  })

  it('initializes the component', () => {
    const wrapper = shallowMount(PlayerFilterTable, { propsData, localVue, store });
  });

Vue组件


<template>
  <div class="player-filter-table">
    <table>
      <tr>
         <th v-for="(key, index) in GetColumns()" 
            v-bind:id="'header-' + key" 
            v-bind:key="index"
            @click="HeaderClick(key)"
          >...</th>
      </tr>
    </table>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
  computed: {
    ...mapGetters({
      allColumns: 'playerFilter/allColumns'
    })
  },
GetColumns() {
  // this.allColumns is defined when running in browser, but undefined when loaded from a Mocha test
  return this.allColumns.filter(column => [*some filter criteria*]);
}
</script>

当shallowMount在test.spec.js中运行时,我希望组件能够成功加载,然后继续运行我的测试,但是相反,我收到一条错误消息,提示TypeError:无法读取未定义的属性“ filter”,因为这。未定义allColumns。

1 个答案:

答案 0 :(得分:0)

modulesnamespaced: true一起使用:

import { createLocalVue, shallowMount } from '@vue/test-utils';
import Vuex from 'vuex';
import PlayerFilterTable from '~/whatever';

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

let propsData, getters, store, wrapper, consoleSpy;

describe('PlayerFilterTable', () => {

  beforeEach(() => {
    consoleSpy = jest.spyOn(console, 'error');
    propsData = {
      players: samplePlayerObject,
      metadata: sampleMetadataObject
    };
    getters = {
      allColumns: () => ["playerid", "last", "first", "birthday", "height"]
    };
    store = new Vuex.Store({
      modules: {
        playerFilter: {
          namespaced: true,
          getters
        }
      }
    });
    wrapper = shallowMount(PlayerFilterTable, {
      propsData,
      localVue,
      store
    });
  });

  afterEach(() => {
    expect(consoleSpy).not.toHaveBeenCalled();
  });

  it('should render correctly', () => {
    expect(wrapper.is(PlayerFilterTable)).toBe(true);
    expect(wrapper.html()).toMatchSnapshot();
  })
})

如果您使用多个模块中的吸气剂,则可以将它们归类到getters的不同属性下,并相应地分配给每个模块。