问题描述
我在写我的第一Koa.js应用程序,最近已推出的ES2016(又名ES7)的功能异步
/ <$ C $的过程C>伺机,我想利用这些。
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.
我发现我的谷歌技能是不达标的任务,code的几小段我能找到要么为标准兴亚(使用发电机)或不-如出血,边缘AS- ES7。
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.
推荐答案
我还是个初学者,所以很可能是很多这可以显着优化,但这里为我工作。
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.
我的 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
- 测试放在这里:
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!');
});
});
摩卡babel.js
,为transpiling测试:
mocha-babel.js
, for transpiling the tests:
'use strict';
require('babel/register')({
'optional': [ 'es7.asyncFunctions' ]
});
我的 index.js
切入点,对巴贝尔transpiling善良的应用程序本身:
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
最后,在脚本的一节我的的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
文件到 ./功能/
目录中,我单位-tests(在这个帖子未显示)插入 ./测试/
其中,摩卡自动找到它们。
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.
我希望这有助于谁像我一样,要使用兴亚与新真棒异步/等待ECMAScript2016 / ES7特点的人。
I hope this helps people who, like me, are trying to use Koa with the new and awesome async/await features of ECMAScript2016 / ES7.
这篇关于如何使用ES2016(ES7)异步在一个Koa.js应用我的验收测试/ AWAIT?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!