Last active
October 28, 2018 13:42
-
-
Save okmttdhr/8dc5ace9d0f766be2fc4fca4856893a2 to your computer and use it in GitHub Desktop.
Vuexのactionをテストする関数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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