测试带有参数返回undefined的Vuex getter不是一个函数

时间:2018-02-23 07:09:41

标签: javascript vue.js vuejs2 chai vuex

我有karma和chai设置,我正在尝试关注测试Getters 示例here

这是我的fruits.js商店代码

// fruits.js store
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const fruits = new Vuex.Store({
  state: {
    fruits: [
      {id: 1, name: 'Apple'},
      {id: 2, name: 'Banana'},
      {id: 3, name: 'Orange'}
    ]
  },
  mutations: {
  },
  actions: {
  },
  getters: {
    getFruitById (state, {id}) {
      return state.fruits.find(fruit => {
        return fruit.id === id
      })
    }
  }
})

这是我的fruit.spec.js文件

// fruit.spec.js
import { expect } from 'chai'
import { fruits } from '../../../../src/store/fruits'

describe('getters', () => {
  it('getFruitById()', () => {
    // mock data
    const state = {
      fruits: [
        {id: 1, name: 'Apricot'},
        {id: 2, name: 'Kiwi'},
        {id: 3, name: 'Watermelon'}
      ]
    }
    const id = 1
    // find fruit by id
    const result = fruits.getters.getFruitById(state, {id})
    expect(result).to.deep.equal([
      {
        id: 1,
        name: 'Apricot'
      }
    ])
  })
})

当我运行fruit.spec.js测试时,它会返回

undefined is not a function

const result = fruits.getters.getFruitById(state, {id})

问题是我fruit.spec.js中的模拟状态未通过fruit.js

如何让测试通过?

1 个答案:

答案 0 :(得分:0)

如果您想对吸气剂进行单元测试,则应单独导出:

// fruits.js store
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export const getters = {
  getFruitById (state, {id}) {
    return state.fruits.find(fruit => {
      return fruit.id === id
    })
  }
}

export const fruits = new Vuex.Store({
  state: {
    fruits: [
      {id: 1, name: 'Apple'},
      {id: 2, name: 'Banana'},
      {id: 3, name: 'Orange'}
    ]
  },
  mutations: {
  },
  actions: {
  },
  getters,
})

然后可以在单元测试中访问以下内容:

import { getters } from '../../../../src/store/fruits'
// ...
    const result = getters.getFruitById(state, {id})
// ....