angular4测试可观测量

时间:2018-02-05 19:27:53

标签: angular testing jasmine

我有一个具有寄存器功能的寄存器组件,我试图测试

  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;
  }));

然而,当我尝试测试注册方法时,我收到一个错误,指出cannot read property subscribe of undefined,它指的是我的register方法中的subscribe调用。我似乎无法从模拟存根中返回一个observable。我做错了什么?

 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()
  }
}

1 个答案:

答案 0 :(得分:1)

这是因为当你spy一个函数时,它实际上并没有被调用,因此this._auth.register没有返回任何内容。你应该让jasmine从register

调用原始函数AuthStub

更改行

let spy = spyOn(auth, "register");

let spy = spyOn(auth, "register").and.callThrough();