Instantly share code, notes, and snippets.

Embed
What would you like to do?
Vuexのactionをテストする関数
import assert from 'assert';
/**
* VuexにおけるActionHandlerが、期待するMutationをcommitするかをテストする。
* Vuexの型はこちらを参照 https://github.com/vuejs/vuex/blob/dev/types/index.d.ts
* @param {*} action テストしたいActionHandler
* @param {*} payload ActionHandlerに渡すpayload。'skip'を指定でテストを無視できる。
* @param {object} state ActionHandlerに渡すActionContextのstate
* @param {array} expectedMutationsAndActions ActionHandlerがcommit/dispatchするオブジェクトの配列。
* @param {object} additionalParams 任意。ActionHandlerに渡すActionContextの追加プロパティ。
* @returns {promise} テスト結果をPromiseで返す。
*/
export const testAction = async (
action: any,
payload: any,
state: Object,
expectedMutationsAndActions: Array<{ type: string; payload?: any }>,
additionalParams: Object = {},
) => {
let count = 0;
const commitAndDispatch = (type, payload) => {
const mutationsAndActions = expectedMutationsAndActions[count];
try {
assert.equal(type, mutationsAndActions.type);
if (payload && mutationsAndActions.payload !== 'skip') {
assert.deepEqual(payload, mutationsAndActions.payload);
}
} catch (error) {
console.log(error);
console.log('actual type', type);
console.log('actual payload', payload);
return Promise.reject(false);
}
count++;
};
await action(
{
commit: commitAndDispatch,
dispatch: commitAndDispatch,
state,
...additionalParams,
},
payload,
);
if (count < expectedMutationsAndActions.length) {
return Promise.reject(false);
}
return Promise.resolve(true);
};
// action.spec.ts
it('get all resources', async () => {
nock(apiServer())
.get(SOME_ENDPOINT)
.query(SOME_QUERY)
.reply(200, {
message: 'OK',
resources: [...]
});
const success = await testAction(
actions.getResources,
null,
STATE_MOCK,
[
{ type: 'request' },
{
type: 'success',
payload: {
resources: [...]
},
},
],
{ rootState: ROOT_STATE_MOCK },
);
expect(success).toBe(true);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment