Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 924
Sathya Narayanan GVK Avatar asked Jul 12 '19 06:07

Sathya Narayanan GVK


People also ask

What is expect in Jest?

When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things. For additional Jest matchers maintained by the Jest Community check out jest-extended .

What is expect assertions in Jest?

expect. assertions(number) will verify that a certain number of assertions are called during a test. Often, this is useful when testing asynchronous code, so as to make sure that assertions in a callback actually got called.

How do you expect a function to be called in Jest?

To check if a function was called correctly with Jest we use the expect() function with specific matcher methods to create an assertion. We can use the toHaveBeenCalledWith() matcher method to assert the arguments the mocked function has been called with.

What are matchers in Jest?

Jest uses "matchers" to let you test values in different ways. This document will introduce some commonly used matchers. For the full list, see the expect API doc.


1 Answers

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
like image 77
Yevhen Laichenkov Avatar answered Oct 29 '22 20:10

Yevhen Laichenkov