测试调用 Getter 和 Mutations 的 Vuex 动作
Posted
技术标签:
【中文标题】测试调用 Getter 和 Mutations 的 Vuex 动作【英文标题】:Test Vuex Action that Calls Getters and Mutations 【发布时间】: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
【问题讨论】:
【参考方案1】:问题是我没有仔细阅读错误消息。基本上,当我需要将调度调用更新为'updateTaxOnLine'
或将操作更改为toggleTaxOnLine
时,我会在'toggleTaxOnLine'
上调用调度,我选择了前者。
【讨论】:
以上是关于测试调用 Getter 和 Mutations 的 Vuex 动作的主要内容,如果未能解决你的问题,请参考以下文章