Angular 角度4测试观察值

Angular 角度4测试观察值,angular,testing,jasmine,Angular,Testing,Jasmine,我有一个寄存器组件,它有一个寄存器函数,我正在测试它 register() { this.hasSubmitted = true; this._auth.register(this.user).subscribe(result => { this.openSnackBar("Registration Successful, Redirecting......", "OK", 2000); setTimeout(() => {

我有一个寄存器组件,它有一个寄存器函数,我正在测试它

  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;
    });
  }
我创建了一个存根类,并将其注入到测试床中,如下所示

 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;
  }));
但是,当我尝试测试register方法时,抛出了一个错误,指出
无法读取未定义的属性subscribe
,这是指我的register方法中的subscribe调用。我似乎无法从模拟存根返回一个可观察的。我做错了什么

 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()
  }
}
it('提交注册后应调用auth类中的register',()=>{
让auth=TestBed.get(AuthService)
让间谍=间谍(auth,“register”);
component.register();
期望(间谍)。已被调用();
});
导出类身份验证存根{
寄存器():可观察{
返回可观察的.empty()
}
}

这是因为当你侦察一个函数时,它实际上没有被调用,因此
这个函数。_auth.register
没有返回任何东西。您应该让jasmine从
AuthStub

换乘线路

let spy=spyOn(auth,“register”)

let spy=spyOn(auth,“register”)。和.callThrough()