我如何在Koa.js应用程序的验收测试中使用ES2016 (ES7) async/await ?
How can I use ES2016 (ES7) async/await in my acceptance tests for a Koa.js app?
我正在编写我的第一个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功能的人。
相关文章:
- Typescript在语法方面与es6/es7有多大不同
- 如何按照承诺使用mocha/chai/chai测试ES7异步函数
- Babel用“es2016”预设实现了尾调用优化
- 在ES2015中,如何确保所有方法都等待对象初始化?使用ES7装饰器
- 如何在我的gulpfile.babel.js中使用ES2016/ES7提案进行async/await
- 浅拷贝对象在 ES6/ES7 中省略一个或多个属性
- 在 ES7 中存根类字段函数
- ES7 类:在构造函数之外声明属性
- 带有 ES3 输出的打字稿 ES7 描述符
- ES7异步功能和promise之间的技术差异
- 在Babel中使用es7函数
- Visual Studio Code ES7/JS Intellisense
- 如何在ES7中等待先前启动的函数
- ES7使用wait生成器从一系列promise中获取结果
- React es7 static childContextTypes意外标记
- 在ES7中使用求幂运算符转换蕴涵逻辑
- 在ES6/ES7中是否有这样的简写
- 我如何在Koa.js应用程序的验收测试中使用ES2016 (ES7) async/await ?
- 在 React.js 中覆盖/扩展 ES7 类的静态属性
- 动态调用JavaScript / ES7类中的静态方法