I have a modal component that gets inputs from outside and, when opened, does send a request to server to get data. After getting data it gets assigned to a public variable and used for showing data. How do I write a test for it? Do i need to mock HttpClient? Or do I have to provide all @Input elements and then do a request as normal? But in that case, i need to have real data for back-end to find in database.
I tried googling for this specific problem, but can't seem to find anything. I did found how to mock requests, but not when they are inside of ngOnInit(). I'll add all the necessary code below.
component:
enum Nav {
General = 'General',
SSL = 'SSL',
Routes = 'Routes',
Statistics = 'Statistics'
};
@Component({
selector: 'app-mod-route-properties',
templateUrl: './mod-route-properties.component.html',
styleUrls: ['./mod-route-properties.component.scss']
})
export class ModRoutePropertiesComponent implements OnInit {
@Input()
title: string;
@Input()
resourceAddress: ResourceAddress;
@Input()
wgsKey: string;
public emsRouteInfoData: EmsRouteInfoData;
public sideMenuItems = Object.values(Nav);
public active: string;
Nav = Nav;
constructor(
private modRoutePropertiesService: ModRoutePropertiesService
) {
}
ngOnInit() {
this.active = Nav.General;
this.modRoutePropertiesService.getRouteProperties(this.resourceAddress, this.wgsKey).subscribe((res: EmsRouteInfoData) => {
this.emsRouteInfoData = res;
}, err => {
console.log(err);
});
}
}
service:
@Injectable()
export class ModRoutePropertiesService {
constructor(
private urlService: UrlService,
private serverSettingsService: ServerSettingsService,
private http: HttpClient
) { }
public getRouteProperties(resourceAddress: ResourceAddress, wgsKey: string) {
let token = this.urlService.getTokenByKey(wgsKey);
let url = this.serverSettingsService.getRequestUrl('/route/properties');
let headers = { 'x-access-token': token };
let params = {
manager: resourceAddress.manager,
node: resourceAddress.node,
qmgr: resourceAddress.qmgr,
route: resourceAddress.objectName
};
const rq = { headers: new HttpHeaders(headers), params: params };
return this.http.get<EmsRouteInfoData>(url, rq);
}
}
test itself:
describe('ModRoutePropertiesComponent', () => {
let component: ModRoutePropertiesComponent;
let fixture: ComponentFixture<ModRoutePropertiesComponent>;
let httpMock: HttpTestingController;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule,
HttpClientTestingModule,
NgbModule.forRoot(),
RouterModule
],
declarations: [
AppComponent,
ModRoutePropertiesComponent,
ModalTitleComponent,
ModRoutePropertiesGeneralComponent,
ModRoutePropertiesSslComponent,
ModRoutePropertiesRoutesComponent,
ModRoutePropertiesStatisticsComponent,
ModRoutePropertiesRouteSelectorComponent
],
providers: [
ModRoutePropertiesService,
UrlService,
TabsService,
{
provide: Router,
useClass: class { navigate = jasmine.createSpy('tab'); }
},
NgbActiveModal,
ServerSettingsService,
ModErrorsDisplayService,
ModalWindowService,
LoadingIndicatorService
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ModRoutePropertiesComponent);
component = fixture.componentInstance;
httpMock = TestBed.get(HttpTestingController);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it(`should init 'active'`, () => {
expect(component.active).toBeDefined();
expect(component.active).toEqual(component.Nav.General);
});
it(`should have initialized 'emsRouteInfoData'`, async(() => {
expect(component.emsRouteInfoData).toBeDefined();
}));
});
I did found a solution. So, in order to test a request call, that is inside of ngOnInit
method, you need to spy on that specific request function, before ngOnInit
is called. Together with spyOn(service, 'function').and.returnValue(Observable.of(object))
it simulates a request call and returns your specified data.
To achieve this, I removed fixture.detectChanges()
on beforeEach()
test stub. The detechChanges()
does trigger a change detection cycle for the component. After that, this is how my beforeEach()
looks like:
beforeEach(() => {
fixture = TestBed.createComponent(ModRoutePropertiesComponent);
component = fixture.componentInstance;
resourceAddress = new ResourceAddress();
resourceAddress.node = 'Node';
resourceAddress.manager = 'MANAGER';
resourceAddress.qmgr = 'T1';
resourceAddress.objectName = 'TestRoute';
// setting inputs
component.resourceAddress = resourceAddress;
component.title = title;
component.wgsKey = wgsKey;
});
And after that, I moved detectChanges()
to specific test case, after I mock a call to desired function getRouteProperties
.
it(`should have initialized 'emsRouteInfoData'`, async(() => {
// needs 'Observable.of()' to simulate real Observable and subscription to it
spyOn(service, 'getRouteProperties').and.returnValue(Observable.of(dummyRoute));
// start ngOnInit
fixture.detectChanges();
expect(service.getRouteProperties).toHaveBeenCalled();
expect(component.emsRouteInfoData).toBeDefined();
}));