How to gather code coverage with Istanbul and Selenium and pitfalls to avoid
How to use Istanbul for code coverage of Cypress automated tests was explained in detail in Testing with Cypress – Custom logging of errors and JUnit results post.
Code coverage with Istanbul and Selenium
Recently I had to do it again, this time with Selenium. There are several approaches, which can be taken to measure code coverage with Selenium. Whichever approach is taken, the first step is to instrument the frontend. How to do it with React and create-react-app is described in Testing with Cypress – Code coverage with Istanbul post. Coverage is present in __coverage__ JS frontend variable.Once the frontend is instrumented, it is important to collect the code coverage after the tests are run. This is where approaches differ. One option is to use istanbul-middleware. In this case, a Node.js backend has to be created and the tests should post the coverage results, taken from coverage to the backend. I find this approach not convenient, so I took the easier one.
Once the test is finished, the code coverage data is collected and saved as a JSON file in a test results folder, then all the results are used to generate the report. I use C# and the code to do so is as simple as:
public void CollectCodeCoverage()
{
var data = ((IJavaScriptExecutor)_webDriver)
.ExecuteScript("return window.__coverage__");
if (data != null)
{
var jsonString = JsonConvert.SerializeObject(data);
var fileName = $"{_testResultsFolder}/coverage_{DateTime.Now.Ticks}.json";
File.WriteAllText(fileName, jsonString);
}
}