Add Jasmine unit testing support to Angular in StackBlitz
I mentioned StackBlitz in the post about online code editors. This service allows for creating i.a. running Angular applications. Once I wanted to execute unit tests written in Jasmine inside it, and I hit a lot of troubles. Finally, I managed to resolve them all.
Table of contents
Install Jasmine
The first part is to add support for Jasmine in StackBlitz. Please follow the series of edits.
Dependencies
Add two packages to your project: jasmine-core and @types/jasmine. Expand the DEPENDENCIES section in file explorer, type the name of the package in enter package name field and press the ENTER key.
Jasmine imports
Create a /src/global-jasmine.ts
file with the following content:
Note: I'll soon be sharing short, practical tips on Angular — a good way to pick up something new if you're interested.
Edit /src/styles.scss
and add import:
Jasmine entry point
And finally, you’ll have to create a file that will be used instead of main.ts
to execute the tests suite.
Add /src/main-testing.ts
file (aside main.ts
) and paste the following content:
Please note the line 24. You’ll have to manually put links to all unit tests you will want to execute.
Unit tests
Create a sample unit test /src/app/app.component.spec.ts
:
That file will be run because it was listed in stuff to test comment in main-testing.ts
. If you want to test other file(s), change the links accordingly.
Run tests
And finally, to run the tests, edit angular.json
and change the line:
"main": "src/main.ts",
to:
"main": "src/main-testing.ts",
To run again the application, change it back.
Sample application
I have created a sample application in StackBlitz: Jasmine in Angular.
Points to improve
There are some things which still require manual work:
- putting all unit tests to
main-testing.ts
file - changing
angular.json
to run the application or tests
Great work, thank you!
I followed your track to prepare the hands-on materials for a lecture about Angular Unit Testing on Stackblitz, doing without the CLI.