I am in the process of writing my first Koa.js app, and having recently been introduced to the ES2016 (aka ES7) features of async
/ await
, I wanted to make use of these.
I found that my Google skills were not up to the task, and the few snippets of code I could find were either for the standard Koa (using generators) or otherwise not-as-bleeding-edge-as-ES7.
See my answer below for how I got my tests running.
I'm still a beginner, so it's likely that a lot of this can be optimised considerably, but here's what worked for me.
I'll basically just dump my files here, they should be fairly straight-forward.
My app.js
:
import koa from 'koa';
import router from 'koa-router';
let koarouter = router();
// Intialize the base application
export const app = koa();
koarouter.get('/', async function() {
this.body = 'Hello World!';
});
// Initialize koa-router
app.use(koarouter.routes());
if (!module.parent) {
app.listen(3000);
console.log('Listening on http://localhost:3000');
}
myapp-spec.js
- the tests go here:
import {app} from '../app';
import * as sap from 'supertest-as-promised';
const request = sap.agent(app.listen());
import chai from 'chai';
const should = chai.should();
describe('/', () => {
it('should return 200 OK', async function() {
const response = await request.get('/');
response.status.should.equal(200);
});
it('should say "Hello World!"', async function() {
const response = await request.get('/');
response.text.should.equal('Hello World!');
});
});
mocha-babel.js
, for transpiling the tests:
'use strict';
require('babel/register')({
'optional': [ 'es7.asyncFunctions' ]
});
My index.js
entry point, for babel transpiling goodness for the app itself:
'use strict';
require('babel/register'); // Imports babel - auto transpiles the other stuff
require('./app'); // this is es6 - gets transpiled
And finally, the scripts section in my package.json
:
"scripts": {
"pretest": "npm run lint -s",
"test:unit": "echo '= test:unit ='; mocha --require mocha-babel",
"test:feature": "echo ' = test:feature ='; mocha --require mocha-babel feature",
"test": "npm run test:unit -s && npm run test:feature -s",
"start": "node index.js",
"lint": "echo '= lint ='; eslint ."
},
Note that I put my *_spec.js
files into the ./feature/
directory, and my unit-tests (not shown in this post) into ./test/
where mocha finds them automatically.
I hope this helps people who, like me, are trying to use Koa with the new and awesome async/await features of ECMAScript2016 / ES7.
来源:https://stackoverflow.com/questions/33369389/how-can-i-use-es2016-es7-async-await-in-my-acceptance-tests-for-a-koa-js-app