Testing
Details
The Angular CLI downloads and install everything you need to test Angular with Jasmine
testing framework.
When you run ng test
, the application is built in watch mode, and lauches the Karma
test runner.
Continuous Integration
You may run in CI (Continuous Integration)
with:
ng test --no-watch --no-progress --browsers=ChromeHeadless
Code Coverage
To generate a coverage report:
ng test --no-watch --code-coverage
Code Coverage Enforcement
Suppose you want the code base to have a minimum of 80% code coverage.
To do so, open karma.conf.js
, and add the check
property in the coverageReport:
key
coverageReporter: {
dir: require('path').join(__dirname, './coverage/<project-name>'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
],
check: {
global: {
statements: 80,
branches: 80,
functions: 80,
lines: 80
}
}
}
Executed Specific Tests
To execetute only specified choosen tests you may append a f
in front of describe
or it
.
// Only this will run
fdescribe(() => { ... });
describe(() => {
// Will be skipped
it(() => { ... });
// Only this will run
fit(() => { ... });
});
Skiping Specific Tests
The same way you can specify choosen tests to skip with a x
in front of describe
or it
.
// Will be skipped
xdescribe(() => { ... });
describe(() => {
// Will be skipped
xit(() => { ... });
// Will run
it(() => { ... });
});
Best Practices
DOM
querying
DOM
queryingWhen writing tests for your Components, you will likely have to query for specific DOM
elements.
It is good practice to add to these specific tested elements a HTML property, working like ids
, so they can easily be reached inside the tests.
Ex.:
<p data-test-id="user-title"> ... </p>
Angular TestBed
TestBed
It creates a dynamically constructed Angular test module that emulates an Angular @NgModule
.
TestBed.configureTestingModule()
TestBed.configureTestingModule()
The TestBed.configureTestingModule()
method takes a metada object that can have most of the properties of an @NgModule
.
WSL Problems/Tips
If you are running tests inside WSL2, it will have problems since it requires Chrome to execute and show the results.
Running npm run test
with --browsers=ChromeHeadless
will help, by avoiding opening a Chrome browser. But it will still require you to install Chrome inside the WSL Ubuntu.
Install Chrome on Ubuntu
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo apt install ./google-chrome-stable_current_amd64.deb
Check to see if google-chrome
autocompletes on the terminal.
Running tests on terminal only
If you just want to run the tests on the terminal just run with:
ng test --no-watch --browsers=ChromeHeadless
See test results on Chrome
Follow here or here to install VcXsrv
on Windows, so that opening Chrome from ubuntu will show graphically on Windows.
Last updated