简体   繁体   中英

How to subscribe and test Observable.of rxjs Angular 9

I'm trying to test a function which returns a rxjs observable, but I cannot subscribe to it in any way. None of the subscribe method that I've tried are working.

"rxjs": "6.5.4","@angular/core": "9.0.1"

Function that i'm trying to test:

isNameValid(c: AbstractControl) {
    const searchResult = this.roles.filter((elem: any) => elem.name?.toLowerCase() === c.value?.toLowerCase());

    if (searchResult.length > 0) {
      c.get('name')?.setErrors({ nameTaken: true });
      return of({ matchError: 'nameTaken' });
    }
    return of(true);
  }

test:

it('should return invalid error if supplied name is taken', () => {
    const nameControl = new FormControl(mock[0].name);
    const isValid = component.isNameValid(nameControl);
    isValid.subscribe
      ({
        next: (result: any) => {
        console.log(result);
        },
        error: (err: any) => {
        console.log(err);
        },
        complete: () => {
        console.log('complete');
        }
        });
  });

What is the correct syntax of subscribing to the observable returned by isNameValid ? Right now, with the pasted syntax(or anything else that I've tried) I cannot get the error free way of subscribing.

Should I write the test differently?

The error that I'm getting is:

Expected 2-3 arguments, but got 1.ts(2554)
Observable.d.ts(51, 39): An argument for 'error' was not provided.

I've also tried:

isValid.subscribe(response => {console.log(response}) which gives the same error.

There seems to be some TypeScript problem not being able to infer return value correctly.

To fix the problem, please provide type definition explicitly for isNameValid method:

isNameValid(c: AbstractControl): Observable<boolean | { matchError: string }> {
  // ...
}

Btw, you can pass an object to subscribe() , this is completely valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM