Problem
(1) I am not able to find a way to trigger a service call in unit test which should be triggered when input is given.
(2)The length of output can be determined based on the input and the length has to be validated in unit test.
Code
<form [formGroup]="sampleFormGroup">
<ng-select class="default" [items]="listItems | async" bindLabel="id"
formControlName="theList" [typeahead]="search" id="mylist">
</ng-select>
</form>
export class AppComponent implements OnInit {
search:Subject<string> = new Subject<string>();
listItems: Observable<any>;
testl:any;
constructor(private formBuilder:FormBuilder,private dataService:ListService){}
public sampleFormGroup = this.formBuilder.group({
theList:[null]
});
ngOnInit(): void {
this.listItems = this.search.pipe(
debounceTime(500),
switchMap(id => this.dataService.getList(id))
);
}
}
export class ListService {
constructor(private http:HttpClient) {}
getList(id:any) {
return this.http.get('https://api.restful-api.dev/objects?id='+id);
}
}
it(`should set sample value as 'Sample Value from service'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
const list = [{"id":"3","name":"Apple"},{"id":"5","name":"Samsung"}];
listService.getList.and.returnValue(of(list));
component.search = new BehaviorSubject('3');
component.listItems.subscribe(resp => {
expect(resp.length).toBe(1);
})
});
Expected result
There are 2 items in the mocked list. If the test input is 3 then the list in the output has 1 item which means that length of the output should be 1.
prachi bhamodre is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.