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

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

本文关键字:ES7 ES2016 async await Koa js 验收测试 应用程序      更新时间:2023-09-26

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

我发现我的谷歌技能无法胜任这项任务,我能找到的少数代码片段要么是针对标准Koa(使用生成器)的,要么是不像es7那么先进的。

我仍然是一个初学者,所以很可能有很多可以优化的地方,但这里是对我有用的。

我基本上就是把我的文件转储到这里,它们应该是相当直接的。


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 -测试到这里:

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入口点,对于应用程序本身的巴别塔翻译的好处:

'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的新的和令人敬畏的async/await功能的人。