Add Jasmine unit testing support to Angular in StackBlitz

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.

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:

TypeScript
/src/global-jasmine.ts

Edit /src/styles.scss and add import:

CSS
/src/styles.scss

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:

TypeScript
/src/main-testing.ts

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:

TypeScript
/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:

  1. putting all unit tests to main-testing.ts file
  2. changing angular.json to run the application or tests

Leave a Reply

avatar
  Subscribe  
Notify of