I'm using Jasmine to test an Angular app and I'm trying to figure out how to test the value of a property that is set in the subscribe
call on an Observable within the component. I've put together an example component here just to illustrate the point.
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent {
public Result[] Items;
constructor(private myService: MyService) {
this.formControl.valueChanges.pipe( switchMap(value => myService.getResults(value)) ).subscribe(results => this.Items = results); } }
In this example, for my test I would be calling getResults()
from within and I'd test to make sure that Items
is populated. Since this is not guaranteed to happen immediately, but the subscribe
logic is entirely within the component, how should I go about awaiting that to make sure I don't get undefined
when I check the value of Items
?
EDIT: Here’s a sample of how I’ve looked at testing it so far. Please note I’ve updated how the comment in the code above indicating that the observable is subscribe as a result of a FormControl value change, not just a button click, hence the detectChanges
below.
it(‘should pull results’, () => {
const componentFixture = TestBed.createComponent(ListComponent);
const component = componentFixture.componentInstance;
const myService = TestBed.inject(MyService);
spyOn(myService, ‘getResults’).and.returnValue(of([myTestItems]));
component.formControl.setValue(‘abcdefg’);
componentFixture.detectChanges();
expect(component.Items).toEqual([myTestItems]);
}