如何解决RxJs:测试依赖于其他 observable 的 observable/
我有一个名为 isSearchEnabled$ 的 observable,它指示搜索表单上的搜索按钮是否可点击。 这是 observable 的代码:
isSearchEnabled$ = anotherObject.errorSource$.pipe(map((errors) => errors.length === 0);
正如人们所见,这个 observable 依赖于另一个 observable,它在每次表单验证发生时发出一个数组。因此,当数组为空时,isSearchEnabled 发出布尔值 true,否则发出 false。
我想测试这个 observable,但我不确定如何测试。我应该模拟 anotherObject.errorSource$
来发出假错误,并检查 isSearchEnabled$
是返回 true 还是 false?
我应该如何在 Angular/RxJS 中做到这一点? 如果有人在旁观者中有解决方案,或者只是常规解决方案,我将非常感激!
PS.:我知道我应该提供一个有效的例子,但我认为这个描述很简单,不需要进一步的代码。
解决方法
如果 anotherObject 是你上面指定的对象,你可以做这样的事情。 AnotherObject Stackblitz
describe("HelloComponent",() => {
let spectator: Spectator<HelloComponent>;
const createComponent = createComponentFactory({
component: HelloComponent,providers: [],detectChanges: false
});
beforeEach(() => {
spectator = createComponent();
});
it("should be disabled",done => {
const errors = [new Error("xyz"),new Error("abc")];
spectator.component.anotherObject = { errorSource$: of(errors) };
spectator.detectChanges();
spectator.component.isSearchEnabled$.subscribe({
next: isSearchEnabled => {
expect(isSearchEnabled).toBeFalse();
//You might want to test here whether your component template/state changed..
done();
}
});
});
it("should be enabled",done => {
spectator.component.anotherObject = { errorSource$: of([]) };
spectator.detectChanges();
spectator.component.isSearchEnabled$.subscribe({
next: isSearchEnabled => {
expect(isSearchEnabled).toBeTrue();
done();
}
});
});
});
如果您从 akita 查询 中获得 observable,最好的选择是模拟您的 observable 所依赖的查询方法。我还没有测试下面的代码,但类似的东西应该可以工作。
let spectator: Spectator<HelloComponent>;
let query: SpyObject<AkitaAnotherObjectQuery>;
const createComponent = createComponentFactory({
component: HelloComponent,mocks: [AkitaAnotherObjectQuery],detectChanges: false
});
beforeEach(() => {
spectator = createComponent();
query = spectator.inject(AkitaAnotherObjectQuery);
//return empty array to check if search is enabled by default
query.selectErrorSource.andReturn(of([]));
});
it('should be enabled',() => {
spectator.detectChanges();
//todo test whether component state changed..
});
//test could be fake async or if you want to test the observable you can subscribe to it in the test below
it('should be disabled',() => {
const errors = [new Error('myError')];
query.selectErrorSource.andReturn(of(errors));
spectator.detectChanges();
//todo test whether component state changed..
});
....
希望它会成功,如果您还有任何问题,请告诉我。如果您愿意,我还可以在 Stackblitz 中添加 akita 查询模拟的示例,请告诉我。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。