![](/img/trans.png)
[英]How to subscribe to a normal function as an Observable in Angular
[英]how to check subscribe function is working in angular?
我想使用茉莉花對組件中存在的我的功能進行單元測試。 在該函數內部存在subscribe
函數。我想測試用戶是否獲得響應的功能ID是否應該導航到/user
組件。
功能
onSubmit(val) {
console.log(val);
this.signupService.signUpHandler(val).subscribe((res:SignUpModel) => {
if (res.token !== '') {
this.router.navigate(['/users']);
}
}, (err) => {
console.log(err);
});
}
這是我的代碼https://stackblitz.com/edit/angular-testing-kdb8ka?file=app%2Fapp.component.ts
我可以檢查我的service
功能是否在單擊按鈕時被調用
it('should called service method on button click', inject([SignupserviceService], (signupserviceService: SignupserviceService) => {
spyOn(signupserviceService, 'signUpHandler');
let button = fixture.nativeElement.querySelector('.btn')
button.click();
expect(signupserviceService.signUpHandler).toHaveBeenCalled();
}));
現在,我想檢查是否從服務獲得響應,然后重定向到
\\user\u003c/code>組件。
假設成功,您只需要監視正在訂閱的函數並返回期望的響應即可:
it('should call the router's navigate method if a non-empty string token property is on the response', inject([SignupserviceService, Router], (signupserviceService: SignupserviceService, router: Router) => {
spyOn(signupserviceService, 'signUpHandler').and.returnValue(Observable.of({token: 'not empty'}));
spyOn(router, 'navigate');
let button = fixture.nativeElement.querySelector('.btn');
button.click();
expect(router.navigate).toHaveBeenCalledWith(['/users']);
})
);
將其視為偽代碼,因為我沒有檢查它是否有錯誤,但是您明白了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.