Last active
October 18, 2018 11:56
-
-
Save matthewp/a8b76736f6c1dd3836453cb7b9666545 to your computer and use it in GitHub Desktop.
Testing with generator functions
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
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' }) } | |
}); | |
}; |
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
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