Skip to content

Adding custom Chai assertions to your Cypress tests

Cypress allows you to add custom assertions as Chai plugins and use them in global scope. I found a good Chai plugin to compare two objects in deep ignoring the order.

To start using the plugin I installed the npm package.

> npm i --save deep-equal-in-any-order
npm WARN retina-backend@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

+ deep-equal-in-any-order@1.0.28
added 3 packages from 4 contributors in 19.987s

55 packages are looking for funding
  run `npm fund` for details

Import the package and add it to chai’s global scope. chai is a global exposed by Cypress which means we can just simply extend it.

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


We can start using this custom assertion.

expect([1, 2]).to.not.deep.equalInAnyOrder([2, 1, 3]);
expect({ foo: [1, 2], bar: [4, 89, 22] }).to.deep.equalInAnyOrder({ foo: [2, 1], bar: [4, 22, 89] });
expect({ foo: ['foo-1', 'foo-2', [1, 2], null ] }).to.deep.equalInAnyOrder({ foo: [null, [1, 2], 'foo-1', 'foo-2'] });
expect({ foo: [1, 2], bar: { baz: ['a', 'b', { lorem: [5, 6] }] } }).to.deep.equalInAnyOrder({ foo: [2, 1], bar: { baz: ['b', 'a', { lorem: [6, 5] }] } });
See also  How to make an Axios POST request?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.