[英]How to subscribe and test Observable.of rxjs Angular 9
I'm trying to test a function which returns a rxjs observable, but I cannot subscribe to it in any way.我正在尝试测试一个返回 rxjs observable 的函数,但我无法以任何方式订阅它。 None of the subscribe method that I've tried are working.
我尝试过的订阅方法都不起作用。
"rxjs": "6.5.4","@angular/core": "9.0.1"
Function that i'm trying to test:我要测试的功能:
isNameValid(c: AbstractControl) {
const searchResult = this.roles.filter((elem: any) => elem.name?.toLowerCase() === c.value?.toLowerCase());
if (searchResult.length > 0) {
c.get('name')?.setErrors({ nameTaken: true });
return of({ matchError: 'nameTaken' });
}
return of(true);
}
test:测试:
it('should return invalid error if supplied name is taken', () => {
const nameControl = new FormControl(mock[0].name);
const isValid = component.isNameValid(nameControl);
isValid.subscribe
({
next: (result: any) => {
console.log(result);
},
error: (err: any) => {
console.log(err);
},
complete: () => {
console.log('complete');
}
});
});
What is the correct syntax of subscribing to the observable returned by isNameValid
?订阅
isNameValid
返回的 observable 的正确语法是什么? Right now, with the pasted syntax(or anything else that I've tried) I cannot get the error free way of subscribing.现在,使用粘贴的语法(或我尝试过的其他任何东西),我无法获得无错误的订阅方式。
Should I write the test differently?我应该以不同的方式编写测试吗?
The error that I'm getting is:我得到的错误是:
Expected 2-3 arguments, but got 1.ts(2554)
Observable.d.ts(51, 39): An argument for 'error' was not provided.
I've also tried:我也试过:
isValid.subscribe(response => {console.log(response})
which gives the same error. isValid.subscribe(response => {console.log(response})
给出了同样的错误。
There seems to be some TypeScript problem not being able to infer return value correctly.似乎有一些 TypeScript 问题无法正确推断返回值。
To fix the problem, please provide type definition explicitly for isNameValid
method:要解决此问题,请为
isNameValid
方法明确提供类型定义:
isNameValid(c: AbstractControl): Observable<boolean | { matchError: string }> {
// ...
}
Btw, you can pass an object to subscribe()
, this is completely valid.顺便说一句,您可以将对象传递给
subscribe()
,这是完全有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.