【发布时间】:2021-08-25 00:13:24
【问题描述】:
我想做的是测试以下调用一些突变和吸气剂的 vuex 动作。我无法判断我的问题是否导致异步/等待问题,或者我并没有真正调用/调度操作代码。
动作
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});
}
});
},
}
测试
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);
});
});
突变
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;
},
};
吸气剂
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),
};
我得到的错误是:
console.error
node_modules/vuex/dist/vuex.common.js:499
[vuex] unknown action type: toggleTaxOnLine
【问题讨论】:
标签: vuex vue-test-utils