Home > Software engineering >  How to check for multiple values in JEST? (OR-operator)
How to check for multiple values in JEST? (OR-operator)

Time:11-03

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' );
});

CodePudding user response:

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);
});
  • Related