首页 > 解决方案 > 使用 Selenium + istanbul 的 javascript 代码覆盖率

问题描述

任何人都可以帮助我在运行 Selenium 测试用例时如何使用伊斯坦布尔获得 JavaScript 代码覆盖率?

我已经通过这个链接,但无法得到它。在我的情况下如何使用它?我的测试在调用远程服务器的本地浏览器中运行。Selenium 测试用例是用 Java 编写的。

标签: javascriptseleniumcode-coverageinstrumentsistanbul

解决方案


https://github.com/alex028502/istanbulseleniumexample

我也很难理解,所以我用 webpack 做了上面的例子。

module.exports = {
  devtool: 'source-map',
  mode: 'none',
  module: {
    rules: [
      // { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
      {
        resolve: {
          extensions: ['.js'],
        },
        use: {
          loader: 'istanbul-instrumenter-loader',
          options: {esModules: true},
        },
        enforce: 'post',
        exclude: /node_modules/,
      },
      {
        test: /\.coffee$/,
        use: [
          {loader: 'coffee-loader'},
        ],
      },
    ],
  },
  entry: './src/index.js',
  output: {
    path: __dirname + '/public/',
    filename: 'index.js',
  },
};

然后如果您在浏览器中运行检测代码,您可以像这样下载它

coverage_info = _driver.execute_script('return JSON.stringify(window.__coverage__);')
# each report needs a unique name
# but we don't care for this example which report corresponds
# to which test
timestamp = datetime.datetime.timestamp(datetime.datetime.now())
file = open("nyc_output/coverage%s.json" % timestamp, 'w')
file.write(coverage_info)
file.close()

然后生成这样的报告

node_modules/.bin/nyc report -t nyc_output

如果您不使用 webpack,您只需像粘贴的示例一样使用命令行检测您的代码,然后它会创建一个包含检测代码的新文件夹。

# from https://medium.com/@the1mills/front-end-javascript-test-coverage-with-istanbul-selenium-4b2be44e3e98
mkdir public-coverage
cp -a public/. public-coverage/   # copy all files over
istanbul instrument public \ 
    --output public-coverage \
    --embed-source true

我可以从你提到的链接中做的部分是伊斯坦布尔中间件


推荐阅读