如何在我的Koa.js应用程序验收测试中使用ES2016(ES7)async / await?

时间:2015-10-27 13:32:34

标签: javascript async-await bdd koa ecmascript-7

我正在编写我的第一个Koa.js应用程序,并且最近已经介绍了async / await的ES2016(又名ES7)功能,我想利用这些

我发现我的谷歌技能不能胜任这项任务,而我能找到的几段代码就是标准的Koa(使用发电机),或者不像ES7那样边缘化。< / p>

请参阅下面的答案,了解我的测试是如何运行的。

1 个答案:

答案 0 :(得分:6)

我还是初学者,所以很可能会有很多优化,但这对我有用。

我基本上只是把我的文件转储到这里,它们应该是相当简单的。

我的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 - 测试在这里:

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,用于转发测试:

'use strict';

require('babel/register')({
  'optional': [ 'es7.asyncFunctions' ]
});

我的index.js入口点,因为babel正在为应用程序本身提供良好的信息:

'use strict';

require('babel/register'); // Imports babel - auto transpiles the other stuff
require('./app'); // this is es6 - gets transpiled

最后,我的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 ."
  },

请注意,我将*_spec.js文件放入./feature/目录,并将我的单元测试(此帖子中未显示)放入./test/,其中mocha会自动找到它们。

我希望这能帮助像我这样的人尝试将Koa与ECMAScript2016 / ES7的新功能和令人敬畏的异步/等待功能结合使用。