byCoder
byCoder

Reputation: 9184

jest.doMock and JSON import mocking

I have such code to test:

...
import data from '../data/mock.json';

// function is async
export const something = async () => {
    try {
        ...
        if (!data) {
          throw 'error is here!';
        }

        return data;
    } catch (error) {
        return error;
    }
};

and my spec looks so:

...
import { something } from './handler';

describe('handler: something', () => {
    beforeEach(() => {
        jest.resetModules();
    });

    describe('on something', () => {
        it('should return data', async () => {
            const data = [
                {
                    id: 1,
                    price: '1',
                },
                {
                    id: 2,
                    price: '2',
                },
            ];

            jest.doMock('../data/mock.json', () => {
                return {
                    __esModule: true,
                    default: data,
                };
            });
            await import('../data/mock.json');

            await expect(something()).resolves.toEqual(data);
        });

        it('should return error', async () => {
            jest.doMock('../data/mock.json', () => ({
                __esModule: true,
                default: undefined,
            }));

            await import('../data/mock.json');

            await expect(something()).resolves.toBe('error is here');
        });
    });
});

not sure why: but it doesn't mock json import inside my code, that I wish to test. What I do wrong and how to make this import mocked 'conditionally'? because if I mock it at the top of the file (nearby imports) - it will work but will be the same for all test cases while I need to make this data different in different test cases.

Upvotes: 2

Views: 3605

Answers (1)

Estus Flask
Estus Flask

Reputation: 222379

jest.doMock cannot affect something because it already uses original mock.json and needs to be reimported, while reimporting mock.json in tests cannot affect anything on its own.

It should be:

    jest.doMock('../data/mock.json', () => ({
        __esModule: true,
        default: undefined,
    }));

    const { something } = await import('./handler');

    await expect(something()).resolves.toBe('error is here');

Upvotes: 2

Related Questions