Dez
Dez

Reputation: 5838

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?

Upvotes: 8

Views: 16985

Answers (2)

Steve Chambers
Steve Chambers

Reputation: 39424

Here is an alternative way of expressing the condition using matchers (can be combined with the approach to extend, as suggested in the answer by @bugs):

expect([expect.any(Boolean), null]).toContainEqual(variable);

Upvotes: 1

bugs
bugs

Reputation: 15313

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

Upvotes: 14

Related Questions