Unit testing plays a very important role when new features are being added in a working functional application, here it reduces the chances of bugs to the rest of the functionality due to the latest changes.
When it comes to Angular, we are using Jasmine and Karma for internal testing. It plays a major role in terms of quality and is an efficient way of writing code.
Jasmine is an open-source testing framework for JavaScript. It aims to run on any JavaScript-enabled platform, to not intrude on the application nor the IDE, and to have easy-to-read syntax.
Jasmine has 3 main methods,
- it()
Declaration of a particular test
- describe()
It’s a suite of tests
- expect()
Expect some value in true form
Karma allows you to execute JavaScript code in multiple real browsers. The main purpose of Karma is to make your test-driven development easy, fast, and effective.
There are 3 types of testing,
- Unit Testing
- Integration Testing
- End-to-End Testing
I assume that Node, NPM, and Angular CLI are configured properly in your system.
Note
Karma currently works on Node.js 6.x, 8.x, and 10.x.
Latest version
- Jasmine: 3.7.1 [2 months ago]
- Karma: 6.3.2 [2 months ago]
Let's get started:
- Download Angular sample code from GitHub. Git clone
- cd Angular-UnitTesting
- npm install
- ng test
Execute these commands
- npm uninstall -g @angular/cli
- npm cache clean
- npm install -g @angular/[email protected]
- npm install --save-dev @angular/cli@latest
- npm install -g @angular/cli@latest
- ng update
- ng update @angular/cli @angular/core
- ng update @angular/cli @angular/core --allow-dirty --force
- ng test
ng test command builds the app in watch mode and launches the Karma.
Conclusion
Writing test cases is a good practice. It will improve the quality and performance of your application. In this article, we learned how to start writing test cases for an Angular application.