首页 > 解决方案 > RxJs:测试依赖于其他可观察对象的可观察对象/

问题描述

我有一个名为 isSearchEnabled$ 的 observable,它指示搜索表单上的搜索按钮是否可点击。这是可观察的代码:

isSearchEnabled$ = anotherObject.errorSource$.pipe(map((errors) => errors.length === 0);

可以看到,这个 observable 依赖于另一个 observable,它在每次表单验证发生时都会发出一个数组。因此,当数组为空时,isSearchEnabled 发出布尔值 true,否则为 false。

我想测试这个可观察的,但我不确定如何。我应该模拟anotherObject.errorSource$发出假错误,并检查isSearchEnabled$返回真还是假?

我应该如何在 Angular/RxJS 中做到这一点?如果有人在旁观者中有解决方案,或者只是常规解决方案,我将不胜感激!

PS.:我知道我应该提供一个工作示例,但我认为这个描述很简单,不需要进一步的代码。

标签: angulartestingrxjsobservableangular-spectator

解决方案


如果 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 中添加一个秋田查询模拟示例,请告诉我。


推荐阅读