Skip to content
Advertisement

Module pattern variable returning undefined in test?

I have the following code below which returns certain data depending on NODE_ENV:

config.js

JavaScript

This works well in my component when I set NODE_ENV. However in my test, I keep getting undefined as a result.

config.test.js

JavaScript

Again, Config.data works fine in my React component when I start it up, but I guess I need to somehow initialize this for it to work in my tests? Any advice would be appreciated!

Advertisement

Answer

First of all, you need to make sure the config module is imported after setting the process.env. So you need to use const { Config } = require('./config') rather than import { Config } from './config'; Because imports are hoisted, and when the IIFE execute, the process.env is not prepared.

Another note is module caching.

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Provided require.cache is not modified, multiple calls to require('foo') will not cause the module code to be executed multiple times. This is an important feature. With it, “partially done” objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

There is an IIFE in your config module, it only executes once when you require('./config') multiple times. The value of process.env in IIFE is also cached. So, you need to use jest.resetModules() to clear the module cache.

E.g.

config.js:

JavaScript

config.test.js:

JavaScript

Test result:

JavaScript

You can try to remove jest.resetModules() to check the logs.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement