Angular: Unit Testing using Jasmine and Karma
Why we need unit testing?
Unit testing ensures that all code meets quality standards before it's deployed. Benefits -
- Any bugs found we can fix it easily
- Save time and money
- It's provide documentation
- Reusable and reliable
- Improve code coverage
- reduces code complexity
What is Jasmine?
Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks.
For more info - jasmine.github.io
What is karma?
Karma is a test runner for JavaScript that runs on Node.js. Using karma to run and test JavaScript code into browser. Also, it provides you a configuration file (karma.conf) you can set there browser and testing framework and some other configuration as well.
For more info - karma-runner.github.io/latest/index.html
How we can use jasmine and karma in angular ?
We are using angular-cli to create application step by step.
Create directory where you have to store all your application related files and npm-packages.
Open command prompt from your work directory- Run following commands into the command prompt.
- npm install -g @angular/cli
- ng new angular-unit-testing
After successfully created application view package.json file. You can see there all required dependencies already installed by angular-cli.
Let's view some of the important files which required for unit testing
- karma.conf.js This is the most important file while doing unit testing. we can set here required configurations like plugins, browser, port and frameworks.
Test entry point - test.ts
The angular-cli configuration of karma uses the file “test.ts”
Now time to write some tests -
- if you create any component by using angular-cli command by default test file created.
Command for create component -
ng g component test
Above command create folder and some files -
inside test.component.spec.ts file we can write our first test
Here are some important things we should know -
- TestBed
TestBed is the primary api for writing unit tests for Angular applications and libraries. It used to configure and initialize the environment unit tests.
- ComponentFixture
The ComponentFixture is a test harness for interacting with the created component and its corresponding element. Access the component instance through the fixture and confirm it exists with a Jasmine expectation: content_copy const component = fixture.
- describe
describe is used to scope tests and it is used to declare them.
- it
it is the function which provide jasmine framework. You can specify here test name and inside function we have several option to match result or write test case according to your need.
Finally to run test -
To run the test use angular-cli command -
ng test
It will open a browser to view the test result-
Note -
I hope this article helps you understand a little bit better how to use the tools to test angular.