lundi 5 février 2018

angular4 testing observables

I have a register component with a register function that I'm trying to test

  register() {
    this.hasSubmitted = true;
    this._auth.register(this.user).subscribe(result => {
      this.openSnackBar("Registration Successful, Redirecting......", "OK", 2000);
      setTimeout(() => {
        this._router.navigate(['/']);
      },1000)
      this.hasSubmitted = false;
    }, (error) => {
      this.openSnackBar(error, "OK", null)
      this.hasSubmitted = false;
    });
  }

I've created a stub class and injected it into the testbed as shown below

 beforeEach((() => {
    TestBed.configureTestingModule({
      declarations: [RegisterComponent],
      imports: [
        ReactiveFormsModule, BrowserAnimationsModule, FormsModule, MatInputModule, MatCheckboxModule, MatIconModule, MatProgressBarModule, MatDialogModule, MatSnackBarModule
      ],
      providers: [
        { provide: AuthService, useClass: AuthStub },
        { provide: Router, useClass: RouterStub },
      ]
    })
      .compileComponents();

      fixture = TestBed.createComponent(RegisterComponent);
      component = fixture.componentInstance;
  }));

However, when I try and test the register method, I get an error thrown saying that cannot read property subscribe of undefined, which is referring to the subscribe call in my register method. I cannot seem to have an observable returned from the mock stub. What am I doing wrong?

 it('should call register in the auth class once registration is submitted', () => {
    let auth = TestBed.get(AuthService)
    let spy = spyOn(auth, "register");
    component.register();
    expect(spy).toHaveBeenCalled();
  });

export class AuthStub {

  register(): Observable<any> {
    return Observable.empty()
  }
}

Aucun commentaire:

Enregistrer un commentaire