Mosius
Mosius

Reputation: 1682

Chai - Expect an object to have deep property of an array ignore order

I need to check if the payment has a property named transactions with expected values:

expect(payment).to.have.deep.property('transactions', [
    TRANSACTION_ID_1,
    TRANSACTION_ID_2,
]);

As the order of transactions is not specified, the test doesn't pass all the time.

How can I solve the problem without changing the test structure?

Note: I've found deep-equal-in-any-order plugin, but it seems it doesn't help.

Upvotes: 2

Views: 2516

Answers (1)

emil
emil

Reputation: 6364

Iterate through array and check if it includes each item.

[TRANSACTION_ID_1, TRANSACTION_ID_2].forEach(id => {
  expect(payment).to.have.deep.property('transactions').that.includes(id);
});

If you need to check transactions is unordered array of expected IDs, then check for the length as well.

expect(payment).to.have.deep.property('transactions').that.has.lengthOf(2);

When transactions has all of the expected ids and has same length of expected ids, then it equals to the expected ids when ordered properly.

Upvotes: 1

Related Questions