尝试单元测试商店,如何使其工作?

时间:2019-04-16 03:35:26

标签: javascript unit-testing vue.js vuex

我有这个store.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const mutations = {
  increment: state => state.count++,
  Changeloading(state, status) { state.loading = status },
  ChangeUserGroup(state, newGroup) { state.userGroup = newGroup; },
  ChangeOriginalRole(state, newRole) { state.originalRole = newRole; }
}
export default new Vuex.Store({
  state: {
    count: 0,
    loading: false, //header, TeamLead, TeamMember
    listUserGroup: [],
    userRole: "",
    originalRole: "",
    userGroup: {}
  },
  mutations,
 ...
})

在我的测试文件store.spec.js

import { expect } from 'chai'
import mutations from '@/store'

// destructure assign `mutations`
const { increment } = mutations

describe('mutations', () => {
  it('INCREMENT', () => {
    // mock state
    const state = { count: 0 }
    // apply mutation
    increment(state)
    // assert result
    expect(state.count).to.equal(1)
  })
})

这是我得到的结果:

变异     1)增加

0通过(75ms)   1个失败

1)突变        增量:      TypeError:增量不是函数

在Context.increment(dist \ webpack:\ tests \ unit \ store.spec.js:13:5)

编辑(4/16/2019)

我又走了一步。我在这里看到应该“导出” store.js中的所有组件,例如:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export const mutations = {...};

export const state = {...};

export const actions = {...};

export const getters = {...};

export default new Vuex.Store({
  state,
  mutations,
  actions,
  getters
});

但是即使那样,我也变得很丑陋(测试失败消息)

0通过(61ms)   1个失败

1)突变        增量:      TypeError:增量不是函数       在Context.increment(dist \ webpack:\ tests \ unit \ store.spec.js:12:5)

1 个答案:

答案 0 :(得分:0)

我终于找到了这个答案: 在我的测试文件中,我有

import { expect } from 'chai'
import mutations from '@/store'

导入突变的正确方法应该是...

import { expect } from 'chai'
import {mutations} from '@/store'

此案已由{}解决:)

此致