Support for code coverage instrumentation in the app code
Created by: Enselic
Just like you can say npm test -- --coverage
I think it would be useful to be able to say npm start -- --coverage
or npm run build -- --coverage
to instrument the app code for code coverage. You could then get code coverage information from end-to-end tests (which IMO are the most useful kind of tests). Here'a simple step-by-step demo to show what I mean:
create-react-app coverage-demo
cd coverage-demo
npm install --save-dev chromedriver istanbul-lib-coverage selenium-webdriver
- To src/App.test.js, add
import { Builder } from "selenium-webdriver";
import libCoverage from "istanbul-lib-coverage";
it("report code coverage after end-to-end testing", async () => {
// Go to site
const builder = new Builder();
const driver = builder.forBrowser("chrome").build();
await driver.get("localhost:3000");
// A real test would do more here of course
// Collect coverage data and report it
const __coverage__ = await driver.executeScript("return __coverage__;");
const map = libCoverage.createCoverageMap(__coverage__);
let result = "";
map.files().forEach(function(f) {
var fc = map.fileCoverageFor(f);
result += `${fc.computeSimpleTotals("s").pct + "%"} for ${f}\n`
});
console.log(result);
await driver.quit();
});
- To
const plugins
in node_modules/babel-preset-react-app/index.js, add the following item last to the array
// TODO: Enable only when '--coverage' is passed to 'npm start/build'
require.resolve('babel-plugin-istanbul'),
npm start
npm test # in another terminal
Expected output:
100% for /home/martinno/src/coverage-demo/src/App.js
100% for /home/martinno/src/coverage-demo/src/index.js
6.9% for /home/martinno/src/coverage-demo/src/registerServiceWorker.js
The coverage data can of course be processed in more useful ways. In my own app I write the json data to files and then use istanbul report --root coverage-data html
to get a nice HTML presentation of coverage data.
Would you be open to a contribution that did step 5 properly?