Get code coverage report for LWC unit tests with JEST

code-coveragelightning-web-componentslwc-jestuiunit-test

I was working on the unit test setup for Lightning Web Components with Jest and tried to figure out how to get a code coverage report but found nothing in the Docs. By running:

sfdx-lwc-jest --coverage

I was able to receive the following coverage information in the terminal:

 PASS  force-app/main/default/lwc/helloWorld/__tests__/helloWorld.test.js
  c-hello-world
    ✓ displays greeting (56 ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 helloWorld.js |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.717 s
Ran all test suites.

However, I did not figure out how to get this as a report file.

Best Answer

After running the command mentioned in the question and checking the project structure again, I saw that a /coverage folder was automatically created that contains a lcov-report. So similar to what you might be used to from other UI frameworks.

Looking at the Jest configuration, it seems to import a default configuration (also for coverage reporting). So theoretically you might also be able to overwrite them if you want to use other reports like junit.

jest.config.js

const { jestConfig } = require('@salesforce/sfdx-lwc-jest/config');

module.exports = {
  ...jestConfig,
  modulePathIgnorePatterns: ['<rootDir>/.localdevserver']
};

Since this was not really documented anywhere yet, I thought it would be useful to share this here in Q&A-style.