How to mock an exported const in jest

后端 未结 8 1706
借酒劲吻你
借酒劲吻你 2020-12-23 18:35

I have a file that relies on an exported const variable. This variable is set to true but if ever needed can be set to false manually

8条回答
  •  礼貌的吻别
    2020-12-23 19:19

    This example will work if you compile ES6 modules syntax into ES5, because in the end, all module exports belong to the same object, which can be modified.

    import { allowThrough } from './allowThrough';
    import { ENABLED } from './constants';
    import * as constants from './constants';
    
    describe('allowThrough', () => {
        test('success', () => {
            constants.ENABLED = true;
    
            expect(ENABLED).toBe(true);
            expect(allowThrough({ value: 1 })).toBe(true);
        });
    
        test('fail, ENABLED === false', () => {
            constants.ENABLED = false;
    
            expect(ENABLED).toBe(false);
            expect(allowThrough({ value: 1 })).toBe(false);
        });
    });
    

    Alternatively, you can switch to raw commonjs require function, and do it like this with the help of jest.mock(...):

    const mockTrue = { ENABLED: true };
    const mockFalse = { ENABLED: false };
    
    describe('allowThrough', () => {
        beforeEach(() => {
            jest.resetModules();
        });
    
        test('success', () => {
            jest.mock('./constants', () => mockTrue)
            const { ENABLED } = require('./constants');
            const { allowThrough } = require('./allowThrough');
    
            expect(ENABLED).toBe(true);
            expect(allowThrough({ value: 1 })).toBe(true);
        });
    
        test('fail, ENABLED === false', () => {
            jest.mock('./constants', () => mockFalse)
            const { ENABLED } = require('./constants');
            const { allowThrough } = require('./allowThrough');
    
            expect(ENABLED).toBe(false);
            expect(allowThrough({ value: 1 })).toBe(false);
        });
    });
    

提交回复
热议问题