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()?
});
})
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With