RxJs:测试依赖于其他可观察/

RxJs: Testing observable that depends on other observable/

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

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

正如你所看到的,这个可观察对象依赖于另一个可观察对象,它会在每次表单验证发生时发出一个数组。所以 isSearchEnabled 在数组为空时发出一个布尔值 true,否则为 false。

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

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