Chai 期待一个深度数组,包括不使用 Chai-Immutable

Chai Expect a deep array to include not working with Chai-Immutable

AssertionError: expected 'List [ List [ 0, "a", 0, 0 ], List [ 0, 0, 0, 0 ], List [ 0, 0, 0, 0 ], List [ 0, 0, 0, 0 ] ]' to include 'a'

我用Chai and chai-immutable.

我正在打电话:

expect(nextState).to.deep.include("a");

为什么这不起作用?

请注意,即使 .include()chai-immutable 覆盖,它的行为与 Chai 在原生数组上的行为一样:

考虑:

expect([
  [0, "a", 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
  [0, 0, 0, 0],
]).to.deep.include("a");

这失败了:

 AssertionError: expected [ Array(4) ] to include 'a'

为了解决这个问题,我看到至少有 2 种单独使用 Chai 的方法(据我所知)。可能还有 Chai plugins 可以帮助您。

使用.flatten

Immutable.js Lists 带有 .flatten(),这会将 Lists 的矩阵展平为单个 List:

expect(new List([
  new List([0, "a", 0, 0]),
  new List([0, 0, 0, 0]),
  new List([0, 0, 0, 0]),
  new List([0, 0, 0, 0]),
]).flatten()).to.deep.include("a");

失败会像这样输出:

AssertionError: expected 'List [ 0, "a", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]' to include 'z'

使用.satisfy

Chai 有一个 .satisfy() 允许更多手动控制的断言:

expect(new List([
  new List([0, "a", 0, 0]),
  new List([0, 0, 0, 0]),
  new List([0, 0, 0, 0]),
  new List([0, 0, 0, 0]),
])).to.satisfy(matrix => matrix.some(row => row.includes("a")));

这避免了压平被测试的值,但是因为 chai-immutable 不会覆盖 .satisfy(),所以失败时的输出不太漂亮:

AssertionError: expected { Object (size, _origin, ...) } to satisfy [Function]