How can I make a Jest test ensure that a value is in an enum?
Asked Answered
P

3

1

This is my first time working with jest. I have a scenario where I want to see if the selected value is in an enum or not. Here is my test case:

    test('Should be valid', () => {
        expect(TestCasesExport.userAccStatus(ACC_STATUS.LIVE)).toContain(MEM_STATUS);
    });

MEM_STATUS is an enum and ACC_STATUS is another enum that has some common values with MEM_STATUS.

When I run this test the received is 'live' and expected was an object i.e. {"LIVE": "live", ...}.

So, what do I change in my test case so that I can ensure that the received value is present in the enum MEM_STATUS?

Perbunan answered 13/9, 2022 at 4:9 Comment(0)
E
3

I have the exact same issue. Checking an objects values expect.any(SomeEnum) will fail with:

TypeError: Right-hand side of 'instanceof' is not callable'

Hopefully jest improves this in future, however here's a workaround allowing you to ensure that a value is in an Enum:

// We can't do expect.any(Currency)
// So check the value is in the enum (as an Object)'s values
// See https://mcmap.net/q/1473498/-how-can-i-make-a-jest-test-ensure-that-a-value-is-in-an-enum
const knownCurrencies = Object.values(Currency);
expect(knownCurrencies.includes(currency));

Elsewhere (eg in object values tests) you'll just have to test that the value is a Number, but the previous code will ensure it appears in the enum.

expect(lastTransaction).toEqual({
  ...
  // expect.any(Currency) won't work
  currency: expect.any(Number),
  ...
});
Elemi answered 6/10, 2022 at 9:8 Comment(0)
R
2

Suggestion

You could use jest-extended library. Specifically toBeOneOf matcher function. https://jest-extended.jestcommunity.dev/docs/

Example

First you have to extend jest

import * as matchers from 'jest-extended';
expect.extend(matchers);

// or
import { toBeOneOf } from 'jest-extended';
expect.extend({ toBeOneOf });

Then use toBeOneOf with Object.values

    test('Should be valid', () => {
        expect(enum).toBeOneOf(Object.values(ENUM));
    });

In your case it would be

    test('Should be valid', () => {
        expect(TestCasesExport.userAccStatus(ACC_STATUS.LIVE)).toBeOneOf(Object.values(MEM_STATUS));
    });
Reubenreuchlin answered 20/8 at 5:7 Comment(0)
M
0

I used a helper function expectEnum:

const expectEnum = <T extends { [key: string]: string }>(enumType: T) =>
    expect.stringMatching(Object.values(enumType).join('|'));

And an example:

enum ESomeEnum {
    black = 'black',
    white = 'white',
}
expect({ type: ESomeEnum.black }).toMatchObject({ type: expectEnum(ESomeEnum) });

Modify this helper fn for your purposes if needed

Jest expect.stringContaining docs

Morell answered 23/3, 2023 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.