1

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?

1 Answer 1

2

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})
// ....
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.