Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  76] [ 3]  / answers: 1 / hits: 185562  / 7 Years ago, thu, march 23, 2017, 12:00:00

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 to prevent some behavior if downstream services request it.


I am not sure how to mock a const variable in Jest so that I can change its value for testing the true and false conditions.


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

More From » reactjs

 Answers
315

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

[#58421] Tuesday, March 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
jarod questions
;