RxJs:测试依赖于其他 observable 的 observable/

时间:2021-03-17 12:05:43

标签: angular testing rxjs observable angular-spectator

我有一个名为 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.:我知道我应该提供一个有效的例子,但我认为这个描述很简单,不需要进一步的代码。

1 个答案:

答案 0 :(得分:1)

如果 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 查询模拟的示例,请告诉我。