'Mock specific config value in jest
I have the following default/config.js file
/* eslint-disable @typescript-eslint/no-var-requires */
require('dotenv').config({
path: require('find-config')('.env'),
});
module.exports = {
cronInterval: process.env.CRON_INTERVAL,
queueName: process.env.QUEUE_NAME || '',
isVisible: process.env.IS_VISIBLE
};
In my index.ts, I have
import config from 'config';
import * as cron from 'node-cron';
const isVisible = config.get<boolean>('isVisible');
const queueName = config.get<string>('queueName');
const cronInterval = config.get<string>('cronInterval');
function startProcess(queueName) {
cron.schedule(cronInterval, () => {});
}
// process starts here
if (isVisible) {
startProcess(queueName);
} else {
logger.info('Wont start')
}
In my unit tests I want to test for both cases of isVisible, while keeping the other config values as they are.
I tried
describe.only('isVisible', () => {
beforeEach(() => {
jest.mock('./../config/default.js', () => ({
isVisible: false
}));
})
it('should not run anything if not visible', () => {
require('./../src/index');
const scheduleSpy = jest.spyOn(cron, 'schedule');
expect(scheduleSpy).not.toHaveBeenCalled();
})
})
This didnt work for me, and it doesnt override the value of isVisible.
I know I could also mock the config.get function like config.get.mockReturnValue(false), but that would then override the values of cronInterval and queueName
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
