期待几个但不是全部正确

Expect several but not all true

假设我有一个数组arr = [true, false, false, true, false]。 我想断言这个数组中正好有两个值是真的。显然,我可以做这样的事情(使用 lodash):

Chai.expect(_.filter(arr, item => item == true)).to.have.length(2)

是否有更多的 Chai-y 或 Jest-y 方法来做到这一点?

没有专门的方法。需要自定义断言。

最接近的断言方法如下:

这两个选项都不适合,因为您的期望值是值类型,并且上面的函数使用 === 进行比较(它可以更改,至少在 Chai 中是这样,但对于我们的情况仍然没有区别)。

// Jest example
describe('arrayContaining', () => {
  const expected = [true, true];

  it('does not match: not enough `true` values received', () => {
    expect([true, false, false]).not.toEqual(expect.arrayContaining(expected));
  });

  it('does not match: not enough toatl values received', () => {
    expect([true]).not.toEqual(expect.arrayContaining(expected));
  });
});

以上两个断言都会失败,这意味着这些断言rules/functions无法发现给定情况下预期值和实际值之间的差异。