Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock a TypeScript enum in my Jest unit tests?

I want to mock an enum in my unit tests. My enum looks like this:

enum OriginalEnum {
    START = 'start',
    EXPORT = 'export',
    SEARCH = 'search'
    END = 'end'
}

The START value always stays in place, as well as the END value, but the in-between enum options change over time. They represent "new" features that are highlighted. After a while an existing enum option might be removed and replaced by another one.

What I want is to be able to test that the classes that work with this enum are jumping back and forth correctly, without having to update my unit tests every time one of the in-between enum options is added/removed.

So, my tests should use another enum, that looks like this:

enum MockedEnum {
    START = 'start',
    NAME_OF_FIRST = 'nameOfFirst',
    NAME_OF_SECOND = 'nameOfSecond',
    END = 'end'
}
like image 412
Joos Avatar asked Oct 15 '25 09:10

Joos


1 Answers

The solution that I found relies on this piece of code:

jest.mock('./../../models/original-enum.ts', () => ({
    OriginalEnum: jest.requireActual('./../mocks/mocked-enum').MockedEnum 
}));

When put at the top of a unit tests file, it sets the contents of the original enum equal to the mocked enum, but only for that test file.

You can still import the mocked enum using import { MockedEnum } from './../mocks/mocked-enum', so that you can work with the mocked enum options inside specific tests.

like image 150
Joos Avatar answered Oct 18 '25 07:10

Joos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!