Skip to content

Instantly share code, notes, and snippets.

@themouette
Last active August 29, 2015 14:22
Show Gist options
  • Save themouette/4c578cca6643650859bf to your computer and use it in GitHub Desktop.
Save themouette/4c578cca6643650859bf to your computer and use it in GitHub Desktop.
Flummox actions testutils
/**
* Simple actions test utils.
*
* This is definitely not the best api, but this is simple.
*
* FIXME override action `_dispatch` and `_dispatchAsync` to remove warning
* FIXME and to deliver a cleaner api
*/
import _ from 'lodash';
function noop() {}
function ensureActionId(actionOrActionId) {
return typeof actionOrActionId === 'function'
? actionOrActionId._id
: actionOrActionId;
}
export function register(actionId, successHandler, errorHandler) {
let _actionId = ensureActionId(actionId);
let _successHandler = successHandler || noop;
let _errorHandler = errorHandler || noop;
let actionMethod = _.find(this, (x) => x._id && x._id === _actionId);
return (...args) => {
try {
let response = actionMethod.apply(null, args);
_successHandler(response);
return response;
} catch(err) {
_errorHandler(err);
}
};
}
export function registerAsync(actionId, beginHandler, successHandler, errorHandler, done) {
let _actionId = ensureActionId(actionId);
let _beginHandler = beginHandler || noop;
let _successHandler = successHandler || noop;
let _errorHandler = errorHandler || noop;
let _done = done || noop;
let actionMethod = _.find(this, (x) => x._id && x._id === _actionId);
return (...args) => {
_beginHandler();
let response = actionMethod(...args);
if (!response.then) {
throw new Error('action ${_actionId} should be async');
}
response
.then((...a) => {
_successHandler(...a);
_done();
}, (...a) => {
_errorHandler(...a);
_done();
})
.catch((err) => { _done(err); });
return response;
};
}
/**
* Use a helper to crate an action for tests
*/
export function createActions(Classname, ...args) {
let action = new Classname(...args);
action._dispatch = action._dispatchAsync = noop;
let wrapper = {
register: register.bind(action),
registerAsync: registerAsync.bind(action)
};
let methods = action.getActionsAsObject();
_.forEach(methods, (method, index) => {
wrapper[index] = (...x) => method.apply(action, x);
wrapper[index]._id = method._id;
});
return wrapper;
}
// create a test action
let action = createActions(SomeActions, extra, args);
// register handlers as actions methods cannot be called directly
let method = action.register(action.myAwesomeAction, successHandler, errorHandler);
// call the decorated method
method(some, args);
// For async methods
let method = action.registerAsync(
action.myAwesomeAction,
beginHandle,
successHandler,
errorHandler,
done // to tell mocha/jasmine/whatever the test is over
);
// call the decorated method
method(some, args);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment