How to mock exported const as a joke

I have a file that uses the exported const variable. This variable is set to true , but if ever needed, it can be set to false manually to prevent some behavior if requested by downstream services.

I'm not sure how to mock the const variable in Jest so that I can change its value to test the conditions true and false .

Example:

 //constants module export const ENABLED = true; //allowThrough module import { ENABLED } from './constants'; export function allowThrough(data) { return (data && ENABLED === true) } // jest test import { allowThrough } from './allowThrough'; import { ENABLED } from './constants'; describe('allowThrough', () => { test('success', () => { expect(ENABLED).toBE(true); expect(allowThrough({value: 1})).toBe(true); }); test('fail, ENABLED === false', () => { //how do I override the value of ENABLED here? expect(ENABLED).toBe(false) // won't work because enabled is a const expect(allowThrough({value: 1})).toBe(true); //fails because ENABLED is still true }); }); 
+5
source share
1 answer

This example will work if you compile the syntax of ES6 modules in ES5, because ultimately all module exports belong to the same object that can be changed.

 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 , and do it with 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); }); }); 
+9
source

Source: https://habr.com/ru/post/1265826/


All Articles