gpt4 book ai didi

Angular Testing 可观察量

转载 作者:行者123 更新时间:2023-11-28 21:22:20 24 4
gpt4 key购买 nike

我有一个寄存器组件,我正在尝试测试它的寄存器功能

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

我创建了一个 stub 类并将其注入(inject)到测试平台中,如下所示

 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 方法时,我收到一条错误消息,指出 cannot read property subscribe of undefined,这是指我的 register 方法中的 subscribe 调用。我似乎无法从模拟 stub 中返回可观察到的值。我做错了什么?

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

最佳答案

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

调用原始函数 register

换行

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

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

关于 Angular Testing 可观察量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48630051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com