1

how do I check if functions returns one of multiple possible values?

My current test function:

const { randomTense } = require('./src/models/functions');

test('Category exists', () => {
    const data = randomTense()
    console.log(data.category)
    expect(data.category).toMatch('past' || 'present' || 'future' );
});
Maurice
  • 141
  • 1
  • 9

1 Answers1

1

You can use the 'toContain' method like below.

Note that this is not a good test as it's not exhaustive or deterministic. This may fail randomly if your data.category is sometimes something else. Imagine that the function randomTense returns four strings in random order: past, present, future and this is a bug. In that case this test will pass three times out of four and because it's random it's impossible (it's harder) to predict when it fails.

Testing random functions isn't really a thing. What you usually do in these cases is to separate the function out into smaller bits and mock the random part.

So instead of having a function that does all the things plus the random selection you take all the logic out of it and only leave the random selection which is usually only a line. Then you mock that functionality for your test and test the other function that returns the options/enums.

const { randomTense } = require('./src/models/functions');

const POSSIBLE_VALUES = ['past', 'present', 'future'];

test('Category exists', () => {
    const data = randomTense();
    expect(POSSIBLE_VALUES).toContain(data.category);
});
Dominik
  • 6,078
  • 8
  • 37
  • 61
  • Thank you! If data.category isn't one of these values then the test needs to fail. – Maurice Nov 02 '21 at 21:41
  • The problem is that this test fails if your function returns one of the following values randomly: `past` `present` `future` and `something else`. In that case the test passes three out of four times making it non-deterministic. – Dominik Nov 02 '21 at 22:04
  • I know. I want it to fail if it returns something else. There are no more options to be returned other than past, present and future. – Maurice Nov 02 '21 at 22:43