Unit Test
Writing angular unit test
describe("a banner component", () => {
let component: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
let service: AuthenticationService;
let sharedService: SharedService;
let httpMock: HttpTestingController;
// register all needed dependencies
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [BannerComponent],
imports: [
HttpClientTestingModule,
RouterTestingModule
]
}).compileComponents(); // compile template and css
});
beforeEach(() => {
injector = getTestBed();
// ways to get root injected service
service = injector.get(AuthenticationService);
httpMock = injector.get(HttpTestingController);
fixture = TestBed.createComponent(ChangePasswordComponent);
component = fixture.componentInstance;
// to trigger changedetection so that template values updated
fixture.detectChanges();
// way to get component injected service
authenticationService = fixture.debugElement.injector.get(
AuthenticationService
);
sharedService = fixture.debugElement.injector.get(SharedService);
h1 = fixture.nativeElement.querySelector("h1");
});
it("getHeaders: should get part headers", () => {
service.getHeaders().subscribe(data => {
expect(data).toEqual({});
});
const req = httpMock.expectOne(
`www.test.com?userName=&roleId=&userId=&widgetTabKey=PART_CLASSIFICATION&tenantId=${service.env.environmentDetails.tenantId}&view=${API_SERVICE_CONSTANTS.WIDGET_SECTION.SUMMARY}&`
);
expect(req.request.method).toBe("POST");
// will trigger flush to resolve all api response
req.flush({});
// verify if any pending request not completed
httpMock.verify();
});
});