Skip to content

Instantly share code, notes, and snippets.

@matthewp
Last active October 18, 2018 11:56
Show Gist options
  • Save matthewp/a8b76736f6c1dd3836453cb7b9666545 to your computer and use it in GitHub Desktop.
Save matthewp/a8b76736f6c1dd3836453cb7b9666545 to your computer and use it in GitHub Desktop.
Testing with generator functions
const action = (name, ...args) => {
return [name, args];
};
const GET_TODOS = Symbol.for('action.getTodos');
const getTodos = action.bind(null, GET_TODOS);
function* route() {
let todos = yield getTodos();
return {
isBase64Encoded: false,
statusCode: 200,
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(todos)
};
}
async function run(gen, context) {
let defaultPerformAction = () => {};
let result = gen.next(value);
while(!result.done) {
let [action, args] = result.value;
let performAction = context[action] || defaultPerformAction;
let value = performAction(...args);
if(value.then) {
value = await value;
}
result = gen.next(value);
}
return result.value;
}
exports.run = run;
exports.route = route;
exports.handler = async function(e) {
let gen = route();
return run(gen, {
[GET_TODOS]() { return db.scan({ TableName: 'todos' }) }
});
};
const assert = require('assert');
const { route, run } = require('./handler.js');
describe('Todos', () => {
it('gets the todos', async () => {
let result = await run(route(), {
[Symbol.for('action.getTodos')]() {
return [{label: 'walk the dog'}, {label: 'pick up dry cleaning'}];
}
});
let data = JSON.parse(result.body);
assert.equal(data.length, 2);
assert.equal(data[0].label, 'walk the dog');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment