Search code examples
javascripttestingecmascript-6jestjs

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?


Solution

  • 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();