How can I use ES2016 (ES7) async/await in my acceptance tests for a Koa.js app?
Asked Answered
H

1

4

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.

Hyacinthus answered 27/10, 2015 at 13:32 Comment(0)
H
6

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.

Hyacinthus answered 27/10, 2015 at 13:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.