我正在编写我的第一个 Koa.js 应用程序,并且最近被介绍了 async
/await
的 ES2016(aka ES7)功能,我想利用这些。
我发现我的 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 transpiling goodness:
'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 的新的和令人敬畏的异步/等待功能一起使用的人。
关于javascript - 如何在 Koa.js 应用程序的验收测试中使用 ES2016 (ES7) async/await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369389/