RxJs 大理石测试:断言失败日志难以理解

RxJs marble testing : Assertion fail log hard to understand

我有这个 Rxjs 测试代码。它是故意失败的,因为我想给你看失败的日志。我觉得很难理解,或者至少我不能流利地阅读它。

谁能给我解释一下是什么意思:$[i].frame = i' to equals i'' ?

import { delay } from 'rxjs/operators';
import { TestScheduler } from 'rxjs/testing';

describe('Rxjs Testing', () => {

  let s: TestScheduler;

  beforeEach(() => {
    s = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });

  it('should not work', () => {
    s.run(m => {
      const source = s.createColdObservable('-x-y-z|');
      const expected = '-x-y-z|'; // correct expected value is '---x-y-z|'

      const destination = source.pipe(delay(2));
      m.expectObservable(destination).toBe(expected);
    });
  });
});

为了帮助您更好地理解输出的情况,让我们首先尝试遵循控制台中的语句。有一个 link 指向错误发生的位置。它位于第 10 行代码,即这一行:

expect(actual).toEqual(expected);

在此行设置断点,运行调试模式下的测试显示 actualexpected 个对象。

actual 值为(以 JSON 格式表示):

[
  {
    "frame": 3,
    "notification": {"kind": "N", "value": "x", "hasValue": true}
  },
  {
    "frame": 5,
    "notification": {"kind": "N", "value": "y", "hasValue": true}
  },
  {
    "frame": 7,
    "notification": {"kind": "N", "value": "z", "hasValue": true}
  },
  {
    "frame": 8,
    "notification": {"kind": "C", "hasValue": false}
  }
]

expected:

[
  {
    "frame": 1,
    "notification": {"kind": "N", "value": "x", "hasValue": true}
  },
  {
    "frame": 3,
    "notification": {"kind": "N", "value": "y", "hasValue": true}
  },
  {
    "frame": 5,
    "notification": {"kind": "N", "value": "z", "hasValue": true}
  },
  {
    "frame": 6,
    "notification": {"kind": "C", "hasValue": false}
  }
]

比较两个数组,可以看到frame属性对于相同索引的每个对象都是不同的。这个奇怪的输出来自 Jasmine 的 toEqual 函数,所以让我们尝试根据上面的值来理解它。来自控制台的这一行

Expected $[0].frame = 3 to equal 1.

表示1的期望值不是1,实际上是3。这部分$[0].frame = 3表示实际值是什么,而这个to equal 1是你作为开发者认为应该的. IE。 expected[0].frame(即 1)不等于 actual[0].frame(即 3)。依此类推,expected[1].frame不等于actual[1].frame...

现在,您可能想知道为什么 actualexpected 会得到这样的值。这在 official docs 上有更详细的解释。当您使用此大理石图 -x-y-z|delay2 单位创建冷可观察对象时,它变为 ---x-y-z| 然后转换为类似的东西 - actual大批。前三个 - 符号表示三个空的、不发光的帧。它们位于位置 0、1 和 2。它们在两个数组中都没有表示。

然后是第一个实际值 x。它表示为 actual 数组 (actual[0]) 中的第一个对象。 x 位于位置 3,因此 frame 属性 具有相同的值。 notification 属性 有一些元数据,例如发出的项目的 value。您可以用相同的方式得出 yz 的值。

旁注:当使用 run() 方法时,帧值变为 1、2、3 等,而不是在不使用 run() 时变为 10、20、30,因为 legacy reasons.