Sathya Narayanan GVK
Sathya Narayanan GVK

Reputation: 939

JEST : Expect() only unique elements in an array

I am writing a test case using jest in to test the data returned from a method.The method returns array of non repeating elements.Now i am trying to use expect() in jest to test whether the array returned from the method has only unique elements.

Returned array from method

arr = [ 'Pizza' ,'Burger' , 'HotDogs'] // All elements are unique

Are there any jest matchers like below to check non repeating elements in array ?

expect(arr).toBeUnique()

Or any logic using existing matchers should be done ?

Upvotes: 7

Views: 5767

Answers (2)

ESV
ESV

Reputation: 7730

This is very similar to Yevhen's answer but I've changed the error message to describe the first duplicate item encountered, like

item 3 is repeated in [1,2,3,3]

at the expense of sorting the array

expect.extend({
  toContainUniqueItems(received) {
    const items = [...(received || [])];
    items.sort();
    for (let i = 0; i < items.length - 1; i++) {
      if (items[i] === items[i + 1]) {
        return {
          pass: false,
          message: () => `item ${items[i]} is repeated in [${items}]`,
        };
      }
    }

    return {
      pass: true,
      message: () => `all items are unique in [${items}]`,
    };
  },
});

Upvotes: 0

Yevhen Laichenkov
Yevhen Laichenkov

Reputation: 8672

There is no built on the method to check that array has a unique value, but I would suggest doing something like that:

const goods = [ 'Pizza' ,'Burger' , 'HotDogs'];
const isArrayUnique = arr => Array.isArray(arr) && new Set(arr).size === arr.length; // add function to check that array is unique.

expect(isArrayUnique(goods)).toBeTruthy();

You can use expect.extend to add your own matchers to Jest.

For example:

     expect.extend({
       toBeDistinct(received) {
         const pass = Array.isArray(received) && new Set(received).size === received.length;
         if (pass) {
           return {
             message: () => `expected [${received}] array is unique`,
             pass: true,
           };
         } else {
           return {
             message: () => `expected [${received}] array is not to unique`,
             pass: false,
           };
         }
       },
     });

and use it:

const goods = [ 'Pizza' ,'Burger' , 'HotDogs'];
const randomArr = [ 'Pizza' ,'Burger' , 'Pizza'];

expect(goods).toBeDistinct(); // Passed
expect(randomArr).toBeDistinct(); // Failed

Upvotes: 18

Related Questions