首页 > 解决方案 > 使用 rxjs 进行弹珠测试时如何暂停和恢复虚拟时间?

问题描述

我正在尝试为同时具有反应性元素和非反应性元素的对象编写测试。我不知道如何写大理石图,所以测试是清晰的。

在下面的测试中,我有一个我正在测试的对象,它既存储一个值又将它发布给一个主题。我想编写测试,以便可以发出一些值、停止虚拟时间并检查一些断言。然后,我想恢复虚拟时间。所以,我想我想使用flush.

下面的测试成功,但不清晰:大理石图source2expected2不对齐,所以我不能真正“看到”测试是否正确编写。如果我source2在第一次调用上面定义expectObservable,那么第二次调用expectObservable永远不会看到任何值。

class StoresLatestValue {
  constructor() {
    this.subject = new Subject();
  }
  emit(value) {
    this.latest = value;
    this.subject.next(value);
  }
}

test("StoresLatestValue works", () => {
  new TestScheduler((actual, expected) => expect(actual).toEqual(expected)).run(
    (helpers) => {
      const { flush, hot, expectObservable } = helpers;
      const obj = new StoresLatestValue();

      // First half of the test
      const source1 = hot("a-b-c");
      const expected1 = "  a-b-c";
      source1.subscribe((val) => obj.emit(val));
      expectObservable(obj.subject).toBe(expected1);
      flush();

      // Check that the latest value is what we expect
      expect(obj.latest).toBe("c");

      // These next two marble diagrams work, but since they don't line up,
      // it's hard to know that the test is written correctly
      const source2 = hot("d-e--");
      const expected2 = "  ----d-e--";
      source2.subscribe((val) => obj.emit(val));
      expectObservable(obj.subject).toBe(expected2);
      flush();

      // Check that the latest value is what we expect
      expect(obj.latest).toBe("e");
    }
  );
});

我尝试将订阅运算符添加^source,但似乎没有帮助。我还尝试使用冷的可观察对象,但我仍然无法编写弹珠,所以一切都很好地排列:

// Making the second observable cold works, but still doesn't line up
const source1 = hot(" a-b-c");
const expected1 = "   a-b-c";
const source2 = cold("  -d-e--");
const expected2 = "   -----d-e--";

// Making them both cold doesn't seem to work at all, nothing is observed
// by the second expectObservable
const source1 = cold("a-b-c");
const expected1 = "   a-b-c";
const source2 = cold("-----d-e--");
const expected2 = "   -----d-e--";

有没有办法编写此测试以使其看起来正确?

标签: javascriptrxjsautomated-testsrxjs-marbles

解决方案


推荐阅读