|
| 1 | +/* global expect */ |
| 2 | + |
| 3 | +const mockAction = async (action, payload, store, expectedMutations, expectedDispatchs) => { |
| 4 | + let countMutation = 0 |
| 5 | + let countDispatch = 0 |
| 6 | + // mock commit |
| 7 | + const commit = async (type, payload) => { |
| 8 | + try { |
| 9 | + if (expectedMutations.length !== 0) { |
| 10 | + const mutation = expectedMutations[countMutation] |
| 11 | + countMutation++ |
| 12 | + await expect(mutation.type).toEqual(type) |
| 13 | + if (payload !== undefined) { |
| 14 | + await expect(mutation.payload).toEqual(payload) |
| 15 | + } |
| 16 | + } |
| 17 | + } catch (e) { |
| 18 | + console.error(`[COMMIT ERROR] ACTION : ${action.name} \n ${e}`) |
| 19 | + } |
| 20 | + } |
| 21 | + // mock dispatch |
| 22 | + const dispatch = (type, payload) => { |
| 23 | + try { |
| 24 | + if (expectedDispatchs.length !== 0) { |
| 25 | + const dispatcher = expectedDispatchs[countDispatch] |
| 26 | + countDispatch++ |
| 27 | + expect(dispatcher.type).toEqual(type) |
| 28 | + if (payload !== undefined) { |
| 29 | + expect(dispatcher.payload).toEqual(payload) |
| 30 | + } |
| 31 | + } |
| 32 | + } catch (e) { |
| 33 | + console.error(`[DISPATCH ERROR] ACTION : ${action.name} \n ${e}`) |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + // call the action with mocked store and arguments |
| 38 | + let result |
| 39 | + try { |
| 40 | + result = await action({ commit, dispatch, ...store }, payload) |
| 41 | + } catch (e) { |
| 42 | + console.error(`[ACTION ERROR] : ${action.name} \n ${e}`) |
| 43 | + } |
| 44 | + // check if no mutations should have been dispatched |
| 45 | + if (expectedMutations.length === 0) { |
| 46 | + expect(countMutation).toEqual(0) |
| 47 | + } else { |
| 48 | + expect(countMutation).toEqual(expectedMutations.length) |
| 49 | + } |
| 50 | + if (expectedDispatchs.length === 0) { |
| 51 | + expect(countDispatch).toEqual(0) |
| 52 | + } else { |
| 53 | + expect(countDispatch).toEqual(expectedDispatchs.length) |
| 54 | + } |
| 55 | + // check if has result should return result |
| 56 | + if (result !== undefined) { |
| 57 | + return result |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export default mockAction |
0 commit comments