Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expect a variable to be null or boolean

I am developing some tests with Jest for a Node.js backend and I need to check out some values that come from a third party. In some cases those values can come as a boolean or as null.

Right now I am checking the variables that fit that situation with:

expect(`${variable}`).toMatch(/[null|true|false]/);

Is there any better way to check them with Jest built in functions?

like image 624
Dez Avatar asked Jan 28 '23 00:01

Dez


1 Answers

What about

expect(variable === null || typeof variable === 'boolean').toBeTruthy();

You can use expect.extend to add it to the in-build matchers:

expect.extend({
    toBeBooleanOrNull(received) {
        return received === null || typeof received === 'boolean' ? {
            message: () => `expected ${received} to be boolean or null`,
            pass: true
        } : {
            message: () => `expected ${received} to be boolean or null`,
            pass: false
        };
    }
});

And use it like:

expect(variable).toBeBooleanOrNull();
like image 57
bugs Avatar answered Feb 06 '23 18:02

bugs