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:

My related project

E-book: How to set up free WordPress platform for IT blogs

Do you want to set up a typical blog but you don’t know how to start, which plugins to use or how to customize the site? I spent a few weeks in total doing that from scratch – from learning the ecosystem to adjusting the platform to my very specific needs. Now I want to share with my experience and make the start easier for you.

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

0 0 votes
Article Rating

Want more?

Share!

Subscribe
Notify of
guest
1 Comment
Inline Feedbacks
View all comments
Augusto Ciuffoletti
Augusto Ciuffoletti
1 year ago

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.

1
0
Would love your thoughts, please comment.x
()
x