What I would like to do is to test the following vuex action which calls a few mutations and getters. I can't tell if my issues cause of async/await issues or that I am not really calling/dispatching the action code.
Actions
export const actions = {
async updateTaxOnLine({dispatch, commit}, {lineId}) {
await commit('toggleTaxOnLine', {lineId});
await dispatch('updateTaxOnAllLines');
},
async updateTaxOnAllLines({getters, commit}) {
getters.receiptLines.forEach(l => {
if (l.add_tax) {
const tax = ((parseFloat(l.amount) / getters.taxLinesBaseAmount) * parseFloat(getters.receipt.tax)).toFixed(2);
console.log(`Setting tax to line ${l.id} calculating (${l.amount} / ${getters.taxLinesBaseAmount}) * ${getters.receipt.tax} = ${tax}`)
commit('setTaxOnLine', {lineId: l.id, tax: tax});
} else {
commit('setTaxOnLine', {lineId: l.id, tax: null});
}
});
},
}
Test
import Vuex from 'vuex';
import {createLocalVue} from "@vue/test-utils";
import {actions, getters, mutations, state} from './index'
let store;
beforeEach(() => {
createLocalVue().use(Vuex);
store = new Vuex.Store({
state,
getters,
mutations,
actions,
});
});
describe('store', () => {
it('set tax on a line sets the amount correctly', async () => {
store.replaceState({
receipt: {
"id": 28,
"created": "2021-01-14T22:41:53.023594Z",
"updated": "2021-06-06T01:52:11.092877Z",
"user": null,
"datetime": "2020-11-21T02:51:00Z",
"subtotal": "96.29",
"tax": "6.74",
"amount": "103.03",
"status": "CODING",
"error_message": null,
"lines": [
{
id: 355,
created: "2021-05-17T05:19:44.424661Z",
updated: "2021-06-05T21:10:04.856432Z",
entry_method: "AZURE_RECEIPT_AI",
quantity: "2.00",
unit_price: "2.99",
tax: null,
amount: "5.98",
personal: false,
add_tax: false, // THIS line is TAXED
},
]
}
});
await store.dispatch('toggleTaxOnLine', {lineId: 355});
expect(store.getters.receipt.lines[0].add_tax).toBeTruthy();
expect(store.getters.receipt.lines[0].tax).toEqual(6.74);
expect(store.getters.taxLinesBaseAmount).toEqual(5.98);
});
});
Mutations
export const mutations = {
toggleTaxOnLine: (state, {lineId}) => {
const foundLine = state.receipt.lines.find(l => l.id === lineId);
foundLine.add_tax = !foundLine.add_tax;
},
setTaxOnLine: (state, {lineId, tax}) => {
const foundLine = state.receipt.lines.find(l => l.id === lineId);
foundLine.tax = tax;
},
};
Getters
export const getters = {
receipt: state => state.receipt,
taxLinesBaseAmount: (state, getters) => getters.receiptLines.reduce((accum, l) => {
if (l.add_tax) {
return parseFloat(l.amount) + parseFloat(accum);
}
return accum;
}, 0),
};
The Error that I get is:
console.error
node_modules/vuex/dist/vuex.common.js:499
[vuex] unknown action type: toggleTaxOnLine