0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

配列内のアイテム順を無視してオブジェクトの比較が行えるChaiのプラグイン

Posted at

目的

Chaiを使ったテストコードで、オブジェクトの比較を行う際に、配列内のアイテム順を無視して比較を行う必要があった。Chaiにはdeep-equal-in-any-orderと言うプラグインがあり、配列内の順番を無視して、「配列内のどこかに同じ値があればパス」として比較をしてくれる。

公式ドキュメント

Chaiのサイトにドキュメントがある。
https://www.chaijs.com/plugins/deep-equal-in-any-order/

TypeScriptで使ってみる

準備

chaiのプラグインなので、インストールが必要。プラグインパッケージとかた情報をインストールする。

$npm install --saveDev deep-equal-in-any-order @types/deep-equal-in-any-order

テストコード内では忘れずにプラグインの使用を宣言すること。

import * as chai from "chai";
import deepEqualInAnyOrder from 'deep-equal-in-any-order';
chai.use(deepEqualInAnyOrder);

コード

まとめると、下のようなコードでテストできる。

typescript
import * as chai from "chai";
import { expect } from "chai";
import deepEqualInAnyOrder from 'deep-equal-in-any-order';

chai.use(deepEqualInAnyOrder);

const leftObj = {
  sameOrder: ['a', 'b', 'c'],
  differentOrder: [1, 2, 3]
};
const rightObj = {
  sameOrder: ['a', 'b', 'c'],
  differentOrder: [3, 2, 1] // 異なる順番の配列。
}

describe("comparing two deep equality methods.", () => {
  it("should deep equal when using 'equal'.", () => {
    expect(leftObj).to.deep.equal(rightObj);
  });
  it("should deep equal when using a plug-in 'equalInAnyOrder'.", () => {
    expect(leftObj).to.deep.equalInAnyOrder(rightObj);
  });
});

実行結果

走らせると、想定どおりdeep.equalを使ったテストは配列内のアイテムの順番の違いが原因でfail。
対照にプラグインを使ってdeep.equalInAnyOrderで比較テストを行った方はpassになる。

 comparing two deep equality.
    1) should deep equal when using 'equal'.
    ✓ should deep equal when using a plug-in 'equalInAnyOrder'.

 1 failing

  1) comparing two deep equality.
       should deep equal when using 'equal'.:

      AssertionError: expected { Object (sameOrder, differentOrder) } to deeply equal { Object (sameOrder, differentOrder) }
      + expected - actual

       {
         "differentOrder": [
      +    3
      +    2
           1
      -    2
      -    3
         ]
         "sameOrder": [
           "a"
           "b"

結論

APIでやり取りされるJSONデーターを扱うテストでは、配列内の順番を無視して比較を行いたい場合が多く、このdeep-equal-in-any-orderプラグインはとても便利。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?