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.