使用 mocha 测试含有 es6 modules 的代码是,需要使用 babel-register 来转化语法。babel-register 跟项目中 web 端的项目共享同一份.babelrc。如下:
{
“presets”: [
[
“env”,
{
“modules”: false,
“targets”: {
“browsers”: [
“> 1%”,
“last 2 versions”,
“not ie <= 8”
]
}
}
],
“stage-2”
],
“plugins”: [
“transform-vue-jsx”,
“transform-runtime”
],
“env”: {
“test” : {
“presets”: [“env”, “stage-2”]
}
}
}
在 windows powershell 中:
set BABEL_ENV=test | mocha –rquire babel-register
这里要注意的是 powershell 中的管理命令连接符是 |,而不是 &&
在 mocha 的 issue 中,有一个是希望加入 –env 标志,但 tj 大神直接说不需要,你干嘛不 set xxx_env && mocha.
底下也有人给了另外的解决办法
Since this still seems to get a lot of traffic I thought I would throw out
a relatively simply solution for people like me who wish there was a –env flag.
What I’ve been doing is add a test/mocha.env.js file in the repo,
and then add –require test/mocha.env.js to mocha.opts:
// mocha.opts–require babel-register–require test/mocha.env.js–timeout 60000
// mocha.env.jsprocess.env.NODE_ENV = ‘test’;