简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM