unit test in angular:
Application testing is the major requirement in all programming languages. Testing the behavior or functionality of the application which must be match with user expectations. In angular two types of application testing may be performed.
Karma: It provides browser environment for testing. It also called angular test runner.
Example:
Step 1: Create new angular project.
Step2 : Create new file(here hello.spec.ts) in app folder
Step 3: Write following code into hello.spec.ts
describe('hellotest' ,() =>{ let expected =''; let notexpected=''; let expectMatch=null; beforeEach(()=>{ expected ='hellotest', notexpected = 'hellotest12', expectMatch = new RegExp(/^hello/); }) afterEach(()=>{ expected ='', notexpected = ''; }) /* it('check test' , ()=> expect('hellotest').toBe('hellotest')); it('check not test' , ()=> expect('hellotest').not.toBe('hellotest12')); */ it('check test' , ()=> expect('hellotest').toBe(expected)); it('check not test' , ()=> expect('hellotest').not.toBe(notexpected)); it('check not test for match' , ()=> expect('hellotest').toMatch(expectMatch)); })
Step 4. Run test using ng test
Step 5: Create new service and test service method. ng g s test
Step 6: Write following code into test.service,ts
import { Injectable } from '@angular/core'; @Injectable() export class TestService { constructor() { } add(a,b) { return a+b; } }
Step 7: Write following code into test.service.spec.ts
import { TestBed, inject } from '@angular/core/testing'; import { TestService } from './test.service'; describe('TestService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [TestService] }); }); it('should be created', inject([TestService], (service: TestService) => { expect(service).toBeTruthy(); })); it('add function must be there', inject([TestService], (service: TestService) => { expect(service.add).toBeTruthy(); })); it('add function should work correctly', inject([TestService], (service: TestService) => { expect(service.add(2,3)).toEqual(5); })); });
Step 8 : run test again ng test
Output