8.ES6测试

转自:http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html

如果测试脚本是用ES6写的,那么运行测试之前,需要先用Babel转码。进入demo04目录,打开test/add.test.js文件,可以看到这个测试用例是用ES6写的。


import add from '../src/add.js';
import chai from 'chai';

let expect = chai.expect;

describe('加法函数的测试', function() {
  it('1 加 1 应该等于 2', function() {
    expect(add(1, 1)).to.be.equal(2);
  });
});

ES6转码,需要安装Babel。


$ npm install babel-core babel-preset-es2015 --save-dev

然后,在项目目录下面,新建一个.babelrc配置文件。


{
  "presets": [ "es2015" ]
}

最后,使用--compilers参数指定测试脚本的转码器。


$ ../node_modules/mocha/bin/mocha --compilers js:babel-core/register

上面代码中,--compilers参数后面紧跟一个用冒号分隔的字符串,冒号左边是文件的后缀名,右边是用来处理这一类文件的模块名。上面代码表示,运行测试之前,先用babel-core/register模块,处理一下.js文件。由于这里的转码器安装在项目内,所以要使用项目内安装的Mocha;如果转码器安装在全局,就可以使用全局的Mocha。

下面是另外一个例子,使用Mocha测试CoffeeScript脚本。测试之前,先将.coffee文件转成.js文件。


$ mocha --compilers coffee:coffee-script/register

注意,Babel默认不会对Iterator、Generator、Promise、Map、Set等全局对象,以及一些全局对象的方法(比如Object.assign)转码。如果你想要对这些对象转码,就要安装babel-polyfill


$ npm install babel-polyfill --save

然后,在你的脚本头部加上一行。


import 'babel-polyfill'
原文地址:https://www.cnblogs.com/sharpest/p/8182988.html