Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects using Chai assertions

I have two arrays of mixed orders

const actualResult = [
  {
    start: '30',
    end: '50',
    locations: ['loc1', 'loc2'],
  },
  {
    start: '20',
    end: '40',
    locations: ['loc3', 'loc4'],
  },
];

const expectedResult = [
  {
    start: '20',
    end: '40',
    locations: ['loc4', 'loc3'],
  },
  {
    start: '30',
    end: '50',
    locations: ['loc2', 'loc1'],
  },
];

I have written the below code to compare them using chai assertions

describe('test1', function () {
  it('expect test', function () {
    expect(actualResult).to.have.length(expectedResult.length);
    for (b of expectedResult) {
      var found = false;
      for (d of actualResult) {
        if (b.start == d.start && b.end == d.end) {
          expect(b.locations).to.have.deep.members(d.locations);
          found = true;
        }
      }
      expect(found).to.be.true;
    }
  });
});

which works fine but I'm interested to know if there are any direct chai assertions that I can perform in one line like

expect(actualResult).to.have.all.nested.members(expectedResult);

or better suggestions.

like image 430
Mohamed Rafiudeen Avatar asked Apr 07 '26 08:04

Mohamed Rafiudeen


1 Answers

You can use deep-equal-in-any-order plugin.

Chai plugin to match objects and arrays deep equality with arrays (including nested ones) being in any order.

It works in a similar way as deep.equal but it doesn’t check the order of the arrays (at any level of nested objects and arrays). The array elements can be any JS entity (boolean, null, number, string, object, array…).

E.g.

const deepEqualInAnyOrder = require('deep-equal-in-any-order');
const chai = require('chai');

chai.use(deepEqualInAnyOrder);

const { expect } = chai;

describe('', () => {
  it('should pass', () => {
    const actualResult = [
      {
        start: '30',
        end: '50',
        locations: ['loc1', 'loc2'],
      },
      {
        start: '20',
        end: '40',
        locations: ['loc3', 'loc4'],
      },
    ];

    const expectedResult = [
      {
        start: '20',
        end: '40',
        locations: ['loc4', 'loc3'],
      },
      {
        start: '30',
        end: '50',
        locations: ['loc2', 'loc1'],
      },
    ];

    expect(actualResult).to.deep.equalInAnyOrder(expectedResult);
  });
});

test result:

  59308311
    ✓ should pass


  1 passing (23ms)
like image 129
slideshowp2 Avatar answered Apr 08 '26 23:04

slideshowp2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!