使用 Istanbul 和 Mocha 覆盖 ES6 代码

Using Istanbul and Mocha to cover ES6 code

我有 Node 代码,用 ES6 编写,我通过发布 mocha --harmony 进行测试。 测试很好 - 一切正常。

现在我想将 coverage 和 istanbul 添加到组合中,但遇到的第一个箭头函数总是出错:

No coverage information was collected, exit without writing coverage information
c:\Users\Guy\Code\alpha-dev\tests\helpers.js:12
    setTimeout(() => {
                ^
SyntaxError: Unexpected token )
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Module._extensions..js (module.js:478:10)
    at Object.Module._extensions..js (c:\Users\Guy\Code\alpha-dev\node_modules\istanbul\lib\hook.js:101:13)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)

这是我尝试过的:

  1. 安装了 istanbul-harmony(来自 git://github.com/gotwarlost/istanbul.git#harmony)作为我的开发依赖。
  2. 运行 以下命令:"./node_modules/.bin/istanbul" cover "./node_modules/mocha/bin/_mocha" -- --harmony tests -R spec
  3. 伊斯坦布尔和 _mocha 的标志组合

我如何 运行 istanbul 覆盖使用 ES6 特性编写的测试?我错过了什么?

刚刚在 LinkedIn Node.JS 组中被一位乐于助人的人解决了这个问题。命令行应该是:

node --harmony ./node_modules/istanbul-harmony/lib/cli.js cover --hook-run-in-context ./node_modules/mocha/bin/_mocha -- --R spec --U exports tests

虽然这很麻烦,但您可以将其放在 package.json 脚本部分,然后从命令行 运行 npm run cover

2016 年 7 月

这是一个 package.json 文件的相关部分,其中包含一个有效的“npm cover”命令,该命令被证明对 es6 模块代码很有用(即包括 es6 importexport) , babel 6, istanbul-1.0-alpha.2

我发布这个是因为我不得不花几个小时从别人的 github 问题线程(现在我找不到)找到解决方案。似乎有很多“解决方案”不再解决覆盖问题或无法轻松适应其他 devDependencies 堆栈。 YMMV.

package.json 个脚本

 "scripts": {
    "clean": "rm -rf ./build ./doc ; mkdir ./build",
    "build": "node_modules/.bin/babel build src/index.js -o build/index.js",
    "doc": "node_modules/.bin/esdoc -c esdoc.json",
    "lint": "node_modules/.bin/eslint src/index.js",
    "lint-test": "node_modules/.bin/eslint test/index.js",
    "test": "node_modules/.bin/mocha --compilers js:babel-core/register --reporter spec --slow 50 --timeout 60000",
    "cover": "node_modules/.bin/istanbul cover node_modules/.bin/_mocha -- -u exports --compilers js:babel-register --timeout 60000",
    "go": "npm run clean && npm run lint && npm run lint-test && npm run test && npm run build"
  },

package.json 开发依赖项

 "devDependencies": {
    "babel": "^6.5.2",
    "babel-cli": "^6.10.1",
    "babel-core": "^6.10.4",
    "babel-preset-es2015": "^6.9.0",
    "coveralls": "^2.11.9",
    "esdoc": "^0.4.7",
    "eslint": "^3.0.1",
    "istanbul": "^1.0.0-alpha.2",
    "mocha": "^2.5.3",
    "should": "^8.3.1"
  },

.babelrc

{
  "presets": ["es2015"]
}

.travis.yml

language: node_js

node_js:
  - 6

install:
  - npm install

script:
  - npm run lint
  - npm run lint-test
  - npm run cover

after_script: 
  - "cat coverage/lcov.info | node_modules/coveralls/bin/coveralls.js"