Chintz
Chintz

Reputation: 61

javascript code coverage using Selenium + istanbul

Can anybody help me on how to get JavaScript code coverage using Istanbul while running Selenium test cases?

I have gone through this link but could not get it. How do I use it in my case? My tests are running in a local browser calling the remote server. Selenium test cases are written in Java.

Upvotes: 4

Views: 2691

Answers (1)

Alex028502
Alex028502

Reputation: 3824

https://github.com/alex028502/istanbulseleniumexample

I had trouble understanding that too, so I made the above example with 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',
  },
};

and then if you are running instrumented code in the browser, you can download it like this

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()

and then generate a report like this

node_modules/.bin/nyc report -t nyc_output

If you are not using webpack, you just instrument your code using the command line as in the example you pasted in, and it creates a new folder with the instrumented code.

# 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

The part that I was able to do without from the link you mentioned is the istanbul middleware

Upvotes: 4

Related Questions