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

杀马特。学长 韩版系。学妹 提交于 2019-11-30 22:51:17

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!