ege*_*and 4 javascript bdd async-await koa ecmascript-7
我在写我的第一Koa.js的应用程序,并且最近已经被引入到ES2016(又名ES7)功能的过程async/ await,我想利用这些.
我发现我的谷歌技能不能胜任这项任务,我能找到的代码片段很少是标准的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');
}
Run Code Online (Sandbox Code Playgroud)
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!');
});
});
Run Code Online (Sandbox Code Playgroud)
mocha-babel.js,为了进行测试:
'use strict';
require('babel/register')({
'optional': [ 'es7.asyncFunctions' ]
});
Run Code Online (Sandbox Code Playgroud)
我的index.js切入点,为babel转换为应用程序本身的好处:
'use strict';
require('babel/register'); // Imports babel - auto transpiles the other stuff
require('./app'); // this is es6 - gets transpiled
Run Code Online (Sandbox Code Playgroud)
最后,我的脚本部分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 ."
},
Run Code Online (Sandbox Code Playgroud)
请注意,我将我的*_spec.js文件放入./feature/目录,并将我的单元测试(未在此帖中显示)放入./test/mocha自动查找的位置.
我希望这能帮助像我这样的人尝试将Koa与ECMAScript2016/ES7的新功能和令人敬畏的异步/等待功能结合使用.
| 归档时间: |
|
| 查看次数: |
1954 次 |
| 最近记录: |