Unit testing for Angular is normally performed with Jasmine (for creating test cases) and Karma (for executing tests).
Angular includes a testing framework with TestBed for setting up and initializing the testing environment.
What is Jasmine
- Jasmine is an open-source JavaScript testing framework.
- It is used to test any type of JavaScript application.
- Jasmine is a BDD (Behavior Driven Development).
- In BDD Test are written in Non-technical language so everyone understands easily.
- By following BDD procedure, Jasmine provides a small syntax to test the smallest unit of the entire application instead of testing it as a whole.
- It does not depend on any other JavaScript frameworks.
- It does not require a DOM, And it has a clean, obvious syntax so that you can easily write tests.
- Jasmine support asynchronous testing.
- Jasmine has the test double functions called spies, A spy can stub any function and track all calls to it and its arguments.
What is Karma
- Karma is a testing automation tool created by the Angular JS team.
- Karma is Open source tool.
- Karma is a tool made on top of NodeJS to run JavaScript test cases.
- This is not a testing framework like Jasmine or Mocha or Chai etc
- It only allows us to run JavaScript test cases written using testing frameworks like Jasmine.
- Karma allow us to execute the test cases on any browsers.
- Karma runs JavaScript test cases against real browsers through Command Line Interface (CLI) rather than virtual browser and DOM. Since, DOM rendering across browsers varies, so for correctness of the test report it uses real browsers.
- It can be configured what all browsers need to be used while running Karma.
- Karma can we configured with continuous integration tools like Travis, Jenkin etc.
Flow of unit text case
- The Angular testing package includes two utilities called TestBed and async.
- TestBed is the main Angular utility package.
- The describe container contains different blocks (it, beforeEach, xit, etc.).
- beforeEach runs before any other block. Other blocks do not depend on each other to run.
//Simple file like calculator.ts
export function Addition(num1: number, num2:number){
return num1+num2;
}
// app.component.spec.ts
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { Addition } from './pages/calculator';
describe('AppComponent', () => {
let component = new AppComponent();
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('Our demo Test Case', () => {
expect(true).toBe(true);
});
it('Message Test',()=>{
expect(component.showMessage("Hello")).toBe("Hello");
});
it('Addition check',()=>{
expect(Addition(10,20)).toBe(30);
expect(Addition(10,20)).toBeLessThan(51);
})
});
- Running tests using => ng test
Comments
Post a Comment