柴 期望一个深层数组包括不使用柴不可变

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

本文关键字:数组 包括不 不可变 一个 期望      更新时间:2023-09-26
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-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'

为了解决这个问题,我看到至少有两种方法可以做到这一点(据我所知),单独使用 Chai。可能还有Chai插件可以帮助您解决此问题。

使用.flatten

不可变.js List带有.flatten(),可以将List矩阵扁平化为单个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]