Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test a function that takes an array and outputs 3 random elements?

I want to test this function using Jest. The problem is that I don't know how I can write the test without adding all the possible outcomes in the toBe(). Any hints are welcomed.

const options = [1, 2, 3, 4]
 const getElements= (options) => {
  const getRandomEl = (list) => list[Math.floor(Math.random() * list.length)];
  return [
    getRandomEl(options),
    getRandomEl(options),
    getRandomEl(options),
  ];

And here is my test:

describe("Helper tests", () => {
    test('We should get 3 random elements from a list', () => {
      expect(mathOperations.getElements([1, 2, 3, 4])).toBe([1, 2, 3] | [2, 3, 4] | [1, 2, 4]); //how to avoid adding all possible combinations in the toBe()?
    });
   })
};

like image 780
Monika Avatar asked Sep 16 '25 11:09

Monika


1 Answers

You cannot test that a single array matches multiple arrays. That is, [1, 2, 3] | [2, 3, 4] | [1, 2, 4] === 0.

As suggested by @Andy, you can test that the output array only has members from the initial array using toSatisfyAll

const list = [1,2,3,4];    
test('We should get 3 elements from a list', () => {
  expect(mathOperations.getElements(list).length.toBe(3);
});

test('We should get random elements from a list', () => {
   expect(mathOperations.getElements(list)).toSatisfyAll((el) => list.includes(el));
});

Having said all this, I think const getRandomEl = (list) => list[Math.floor(Math.random() * list.length)]; is the function that makes more sense to be tested since its name is actually meaningful whereas getElements doesn't to much besides calling getRandomEl and adding that three times to an array.

like image 114
Juan Mendes Avatar answered Sep 18 '25 23:09

Juan Mendes