How to set up Angular code coverage in VS Code
Here's how to set up code coverage for your Angular project.
In less than 30 seconds.
If you're testing your Angular project then here's a few high-fives for being an awesome developer.
✋ ✋ ✋
Testing your Angular code is a powerful way to go from a novice developer to a true expert.
But do you know what's even cooler?
Configuring and using code coverage tools in your Angular project.
Code coverage is a great way to get a realistic sense of how effective your testing efforts are. As well as giving you an idea as to what pieces of your Angular app are being tested properly - and the pieces that are being missed. Without code coverage it's hard to get an accurate sense of the effectiveness of our testing efforts.
Without any more rambling... here's how to do code coverage in Angular - in less than 30 seconds.
Three.
Two.
One.
LET'S GOO! 🏎️ 🏎️
1. Change the angular.json
Open the angular.json
file in the root folder of your Angular project.
Scroll to the test
section and add the codeCoverage: true
line.
Like this.
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
...
"codeCoverage": true
}
},
Now, when you restart the Angular testing process, you'll see a new folder in your project called coverage
. This is the code coverage report for your Angular application.
2. Set up the code coverage report in Visual Studio Code.
So now that we've got our code coverage reports generated, how do we show them?
Well, there's an extension that will do this for us. It's called Coverage Gutters.
Go to Extensions in VS Code, search for Coverage Gutters
and install it.
Once installed, you'll see green lines to show what part of your Angular code is being tested.
3. Start tests
This step is as simple as quacking like a duck. 🦆
Run the following command in the root directory of your project to generate the coverage
folder that Coverage Gutters uses to give us a code coverage report.
ng test
4. Start Coverage Gutters
And last of all, use the CTRL + SHIFT + P
shortcut to open the commands window and select Coverage Gutters: Watch
to show the code coverage status in Visual Studio Code.
Conclusion
Don't forget that Angular code coverage isn't a silver bullet. Just because 100% of the code in your Angular project is being tested doesn't mean that all the possible use cases and production scenarios are bug free.
That said, code coverage is a great thermometer to help you decide how many tests you need to write.
What do you think of Coverage Gutters? Let me know in the comments below.
Angular Consultant