chai-recursive-match

npm package Build Status Issues Semantic Release

轻松在 Chai 断言中进行递归比较

关键特性

此 Chai 插件扩展了 Chai 的断言功能,允许对对象和数组进行无缝的递归比较。

它使您能够为嵌套结构编写简洁且表达力强的测试,从而确保数据在每个级别上的完整性。

  • 🔎 递归相等:断言两个对象或数组在递归上相等,同时考虑嵌套值及其类型。
  • 📦 递归包含:验证嵌套值是否存在于对象或数组中,即使它位于结构的深处。
  • 🔧 可定制的匹配器:使用 Chai 丰富的库中的匹配器为嵌套值定义特定的条件,例如类型检查、字符串模式或数值范围。
  • ℹ️ 信息丰富的错误消息:当断言失败时,收到清晰详细的错误消息,指出嵌套结构中差异的确切路径。

安装

尝试一下,用 Chai 增强您的测试体验。

npm install -D chai-recursive-match

注意:无需单独为 TypeScript 安装类型 - 它们已包含在内。

用法

import { use } from 'chai';
import { chaiRecursive } from 'chai-recursive-match';

use(chaiRecursive);

API

递归相等

一个对象或一个数组将与一个模式进行比较。有关模式的类型定义,请参阅 types.ts

一个简单的例子

expect({ foo: { bar: 'baz' } }).to.recursive.equal({
  foo: to => to.recursive.equal({ bar: to => to.be.a('string') }),
});

一个数组示例

expect([{ foo: { bar: 'baz' } }, { foo: { bar: 'foobar' } }]).to.recursive.equal([
  { foo: to => to.recursive.equal({ bar: to.be.a('string') }) },
  { foo: to => to.recursive.equal({ bar: to.match(/^foo/) }) },
]);

一个完整的例子

expect({
  num1: 1,
  num2: 2,
  arr1: [1, 2, 3],
  arr2: [{ id: 1 }, { id: 2 }],
  str1: 'hello 1',
  str2: 'hello 2',
  obj1: { key: 'a', value: 'A' },
  obj2: { key: 'b', value: 'B' },
  method1() {},
}).to.recursive.equal({
  num1: 1,
  num2: to => to.be.gt(1),
  arr1: [1, 2, 3],
  arr2: to => to.deep.contain({ id: 2 }),
  str1: 'hello 1',
  str2: to => to.match(/^hello/),
  obj1: { key: 'a', value: 'A' },
  obj2: to => to.recursive.equal({ key: 'b', value: to => to.be.a('string') }),
});

检查数组是否具有成员

这类似于 recursive.include,但该值应该完全匹配模式

expect([
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
]).to.recursive.equal({ id: 1, name: to => to.contain('A') });

检查数组是否具有成员

这类似于 recursive.have(),用于比较多个成员

expect([
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 2, name: 'Carol' },
]).to.recursive.have.members([
  { id: 1, name: to => to.contain('A') },
  { id: 3, name: to => to.contain('C') },
]);

带否定

expect({ foo: { bar: 'baz' } }).to.not.recursive.equal({
  foo: to => to.recursive.equal({ bar: to => to.be.a('number') }),
});

递归包含

一个对象示例

expect({ foo: { bar: 'baz' }, num: 123 }).to.recursive.include({
  num: to => to.be.gt(100),
});

一个数组示例

expect([{ foo: { bar: 'baz' } }, { foo: { bar: 'foobar' } }]).to.recursive.include({
  foo: to => to.recursive.equal({ bar: to.match(/^foo/) }),
});

检查数组是否包含成员

expect([
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 2, name: 'Carol' },
]).to.recursive.include.members([{ name: to => to.contain('A') }, { name: to => to.contain('C') }]);

带否定

expect([{ foo: { bar: 'baz' } }, { foo: { bar: 'foobar' } }]).to.not.recursive.include({
  foo: to => to.recursive.equal({ bar: to.match(/^baz/) }),
});

待定

  • 🚧 在错误消息中显示差异
  • 🚧 支持 chai.assert 接口
  • 🚧 支持更多数组方法(例如 to.recursive.have.ordered.members