`I want to unit test my subscribe functions. Please help me out. ts
export class EmployeeFormDetailsComponent implements OnInit {
employeeData : any;
id !: number;`your text`
constructor(private api: ApiService) { }
ngOnInit(): void {
this.getEmployeeDetails();
}
getEmployeeDetails(){
this.api.getEmployee()
.subscribe(res =>{
this.employeeData= res;
console.log(res);
})
}
deleteEmployee(row : any){
this.api.deleteEmployee(row.id)
.subscribe(res=>{
this.getEmployeeDetails();
)
}
postEmployeeDetails() {
this.employeeModelObj.firstName = this.registrationForm.value.firstName;
this.employeeModelObj.lastName = this.registrationForm.value.lastName;
this.employeeModelObj.startDate = this.registrationForm.value.startDate;
this.employeeModelObj.endDate = this.registrationForm.value.endDate;
this.employeeModelObj.experience = this.registrationForm.value.experience;
this.api.postEmployee(this.employeeModelObj)
.subscribe(res => {
console.log(res);
this.router.navigate(['employeeFormDetails'])
})
}
getEmployeeDetails(Experience: string) {
this.filteredList = this.api.getemployeeByExperience(Experience)
console.log(this.filteredList);
}
} ````your text`
I have written a unit test case for my get method and it has worked.. But I want to unit test for my delete method, get by experience method and my post method. spec.ts
it('should call get method', ()=>{
const response: EmployeeModel[] =[];
spyOn(service, 'getEmployee').and.returnValue(of(response))
component.getEmployeeDetails();
fixture.detectChanges();
expect(component.employeeData).toEqual(response);
});
CodePudding user response:
Did you try using fakeAsync? Should look somewhat like this:
it('should call get method', fakeAsync(()=>{
const response: EmployeeModel[] =[];
spyOn(service, 'getEmployee').and.returnValue(of(response))
component.getEmployeeDetails();
tick();
fixture.detectChanges();
expect(component.employeeData).toEqual(response);
}));
To be fair, this component seems rather complex. Using subscribe inside components becomes rather tricky anyways, I believe you should consider using a pattern like this: https://blog.angular-university.io/angular-component-design-how-to-avoid-custom-event-bubbling-and-extraneous-properties-in-the-local-component-tree/