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)