Search code examples
javascriptvue.jsvuejs2chaivuex

Testing Vuex getters with argument returns undefined is not a function


I have karma and chai setup and I am trying to follow the Testing Getters example here

Here is my code for fruits.js store

// 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
      })
    }
  }
})

Here is my fruit.spec.js file

// 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'
      }
    ])
  })
})

When I run my fruit.spec.js test it returns

undefined is not a functionon line const result = fruits.getters.getFruitById(state, {id})

The problem is that my mock state in fruit.spec.js is not passed in fruit.js

How can I make the test pass?


Solution

  • If you want to unit test your getters, you should export them separately:

    // 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,
    })
    

    This can then be accessed as following in the unit test:

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