Skip to content

Instantly share code, notes, and snippets.

@zaceno
Created February 6, 2023 09:22
Show Gist options
  • Save zaceno/d44a4b6a026a1d8827c35a602244599b to your computer and use it in GitHub Desktop.
Save zaceno/d44a4b6a026a1d8827c35a602244599b to your computer and use it in GitHub Desktop.
Utility for testing app logic
/**
* Utility for testing hyperapp app/state logic. Pass it an init parameter
* and an effectHandler - a function that will replace every effecter used
* it will be called with (originalEffecter, payload) every time an effect
* is used allowing you to ovverride it and test that the right effecter
* was called, et c.
*
* Returns an object with some useful functions: getState allows you to
* inspect the state at any time, stop stops the app. dispatch dispatches
* actions.
*
* Subscriptions not supported yet. Nor views - but views are beyond
* the scope/purpose of this. This is just for state-logic.
*
*
* @template S
* @param {import('hyperapp').Dispatchable<S>} init
* @param {<X>(effecter: Effecter<S,X>, payload:X)=>void} effectHandler
* @returns {{
* getState: () => S,
* stop: () => void,
* dispatch: import('hyperapp').Dispatch<S>
* }}
*/
export const default (init, effectHandler = () => {}) => {
/**@type {<X>(effecter: import('hyperapp').Effecter<S,X>) => import("hyperapp").Effecter<S,X>} */
const getMockEffect = effecter => (dispatch, payload) => {
effectHandler(effecter, payload)
}
/**@type {S} */
let state
const dispatch = app({
init: init,
dispatch: dispatch => (action, payload) => {
if (Array.isArray(action)) {
if (typeof action[0] !== "function") {
state = action[0]
//@ts-ignore
action = [
action[0],
...action
.slice(1)
//@ts-ignore
.map(f => (typeof f === "function" ? getMockEffect(f) : [getMockEffect(f[0]), f[1]])),
]
}
} else if (typeof action !== "function") {
state = /**@type {S}*/ (action)
}
dispatch(action, payload)
},
})
const getState = () => state
//@ts-ignore
const stop = () => dispatch()
return { getState, dispatch, stop }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment