SharePoint Framework (SPFx). Custom Karma configuration for different test result and coverage reports.
Introduction
This post will describe how to customize Karma configuration for SharePoint Framework (SPFx) web part projects with Office UI Fabric React created/generated with Yoman SharePoint Generator including:
- Generate test result report in JUnit format (ex.: for VSTS CI dashboard)
- Generate test coverage report in text (console) format
- Generate test coverage report in Cobertura format (ex.: for VSTS CI dashboard)
Steps
1. Create SPFx React web part project (skip if you already have one)
Create your SharePoint Framework React web part project using the instructions/steps from “Scaffold projects by using Yeoman SharePoint generator”.
2. Create/run your unit test(s)
Create your unit tests and run them by executing
You should get list of successfully executed uni tests, ex:
3. Custom Karma config setup
The default configuration of Karma test runner comes with sp-build-web
package and is available
inside node_modules
folder:
@microsoft/sp-build-web/lib/karma/karma.config
In order to customize the default/predefined configuration a custom config needs to be created.
Create custom Karma config file karma.config.js
inside folder <your_project_folder>/config
:
We inherit our custom configuration from the default one. In order to enable new custom Karma config file we need to update gulp.js
config. Add the following lines to gulp.js
:
4. Setup JUnit reporter
Install karma-junit-reporter
package as Dev dependency:
The following steps needs to be done to enable JUnit reporter in Karma:
- add JUnit reporter to the list of configured reporters (default are
test-result
,mocha-clean
,coverage
) - provide JUnit reporter configuration
- add karma-junit-reporter plugin to the list of configured plugins
The below lines of karma.config.js combine all three steps:
Run
Once executed check folder <your_project/>temp/testResult
- it will contain file TESTS-PhantomJS_*.xml
which contains test results in JUnit format.
5. Setup console coverage reporter
In order to diaplsy test coverage report in text/console format we need to expand the list
of preconfigured coverage reporters (html
and json
). Add the following configuration to karma.config.js:
Run
and your console output will contain full coverage report, ex:
6. Setup Cobertura coverage reporter
Since Karma has built-in Cobertura coverage reporter the setup is similar to the previous step: add cobertura reporter to the list of configured coverage reporters in karma.config.js:
Run
Once executed check folder <your_project/>temp/coverage
- it will contain file cobertura.xml
which contains test coverage results in Cobertura format.
7. Enjoy your test and test coverage reports!
Full source of karma.config.js is below: