我正在编写我的第一个 Koa.js 应用程序,并且最近被介绍了async
/的 ES2016(又名 ES7)特性await
,我想利用这些特性。
我发现我的 Google 技能无法胜任这项任务,而且我能找到的几段代码要么用于标准 Koa(使用生成器),要么与 ES7 不一样。
请参阅下面的答案,了解我是如何运行测试的。
我正在编写我的第一个 Koa.js 应用程序,并且最近被介绍了async
/的 ES2016(又名 ES7)特性await
,我想利用这些特性。
我发现我的 Google 技能无法胜任这项任务,而且我能找到的几段代码要么用于标准 Koa(使用生成器),要么与 ES7 不一样。
请参阅下面的答案,了解我是如何运行测试的。
我仍然是一个初学者,所以很可能其中很多都可以进行相当大的优化,但这对我有用。
我基本上只是在这里转储我的文件,它们应该相当简单。
我的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 的新的和很棒的 async/await 功能一起使用的人。