0

Here I have written my vuex store file for state management. But I don't know how to test this file.

products.js

import products from '../api/products';
export function getProductById (products, id) {
    const index = products.findIndex(
      products => products.id === id
    )
    let product = null
    if (index !== -1) {
      product = products[index]
    }

    return {
      index,
      product,
    }
}

const initialState = {
  products: [],
  searchText: '',
  productLoading: false,
  productDetail:{},
};

const getters = {
  products: state => {
        if (state.searchText) {
          const reg = new RegExp(state.searchText.trim().toLowerCase().replace(/\s+/g, '|'))
          return state.products.filter(
            product => product.name.toLowerCase().search(reg) !== -1
          )
        } else {
          return state.products
        }
    },

    searchText: state => state.searchText,
};

const actions = {
    fetchProducts({ commit }) {
        return products.getProducts()
            .then(({ data }) => {
                commit(SET_PRODUCTS,data)
            })
            .catch((error) => {
              if(error.response.status === 403){
                commit(SET_PERMISSION_DENIED)
              }
              return Promise.reject(error.response.data);
            }
        );
    },
    createProduct({ commit }, { product_code, name, description, link_to_amazon, price, photo, category }) {
        return new Promise((resolve, reject) => {
          products.createProduct(product_code, name, description, link_to_amazon, price, photo, category)
          .then((res) => {
            resolve(res.data)
          })
          .catch((error) => {
            reject(error.response)
          });
        })
    },

    updateProduct({ commit }, {id, product_code, name, description, link_to_amazon, price, photo, category}) {
        return new Promise((resolve, reject) => {
          products.updateProduct(id, product_code, name, description, link_to_amazon, price, photo, category)
          .then((res) => {
            resolve(res.data)
          })
          .catch((error) => {
            commit(PRODUCT_LOADING, false)
            reject(error.response)
          });
        })
    },

    deleteProduct({ commit }, { id }) {
        return new Promise((resolve, reject) => {
          products.deleteProduct(id)
          .then((res) => {
            commit(REMOVE_PRODUCT_BY_ID,id)
          })
          .catch((error) => {
            reject(error.response)
          });
        })
    },

    setSearchText ({ commit }, value) {
      commit(SET_SEARCH_TEXT, value)
    },
};

const mutations = {
  [SET_PRODUCTS](state, products) {
    state.products = products;
  },
  [PRODUCT_LOADING](state, value) {
    state.productLoading = value;
  },
  [REMOVE_PRODUCT_BY_ID](state,value){
    const { index } = getProductById(state.products, value)
    if (index !== -1) {
        state.products.splice(index, 1)
    }
  },
};

All I want it to test this file, I really don't know how to do that, I have looked into the vuex documentation too. But didn't understand any.

Jinal Somaiya
  • 1,931
  • 15
  • 29
amit
  • 353
  • 1
  • 3
  • 19

1 Answers1

0

you can write a black-box like following:

import storeConfig from '@/store/modules/salesStore'
import { createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'

jest.mock('@/api/sales', () => ({
   fetchInvoices: jest.fn().mockReturnValue([{id: 1, date: 146352542, title:'John Doe' }]),
   deleteInvoice: jest.fn()
})

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

const createStore = () => new Vuex.Store(storeConfig)
describe('sales store', () => {
   it('should be empty by default', () => {
     let store = createStore()
     expect(store.getters.invoices).toBeTruthy()
     expect(store.getters.invoices.length).toBe(0)  
   })

   it('loadInvocie action gets the incoice form the end-point', async () => {
     const store = createStore()
     await store.dispatch('loadInvoices', { departmentId: 1 })
     expect(store.getters.invocies).toEquals([{
       id: 1,
       title: 'John doe',
       date: 146352542
     }])
   }) 
 
})
Siamand
  • 1,080
  • 10
  • 19