Your-First-Angular-Testing (Part 2)
Hi Friends, This is Lakshman here.
Welcome back to the Series Angular Best Practices
Today, We will go through Part 2 of your First Testing in Angular App.
If you do not check Part-1 Check this out
Angular Testing
In this blog, we will discuss the multiple options of testing Services.
The Service consists of * Fetch or Post Data to get Response from API. * Common Functionality such as Validation, Data Conversion, etc.,
The Difficult part only for API Calls because we can't use the API directly.
We need to Mock the API to get the Response.
Sample Testing for Service as below,
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { getTestBed, TestBed } from '@angular/core/testing';
import { environment } from '@env/environment';
import { TempTests } from './test.service.mockdata';
import { TestService } from './test.service';
describe('TestService', () => {
let service: TestService;
let injector: TestBed;
let httpClient: HttpClient;
let httpMock: HttpTestingController;
let testUrl: string;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [TestService]
});
// Inject the http service and test controller for each test
injector = getTestBed();
service = TestBed.inject(TestService);
httpClient = TestBed.get(HttpClient);
httpMock = TestBed.get(HttpTestingController);
testUrl = environment.ServerUrl + 'Test';
});
it('should be created', () => {
expect(service).toBeTruthy();
});
describe('Code Testing', () => {
it('GetTests should return data', () => {
service.GetTests().subscribe((res: any) => {
expect(res).toEqual(TempTests);
});
const req = httpMock.expectOne(testUrl);
expect(req.request.method).toBe('GET');
req.flush(TempTests);
});
it('GetTests should return No data', () => {
service.GetTests().subscribe((res: any) => {
expect(res).toEqual([]);
});
const req = httpMock.expectOne(testUrl);
expect(req.request.method).toBe('GET');
req.flush([]);
});
});
});
On-road head, we will discuss a lot of things.
Looking forward to your comments and share your feedback.
Until that, I am Lakshman, Signing Off.
Comments
Post a Comment