How to determine if JEST is running the code or not?

18,132

Solution 1

jest sets an environment variable called JEST_WORKER_ID so you check if this is set:

function areWeTestingWithJest() {
    return process.env.JEST_WORKER_ID !== undefined;
}

I also see that if NODE_ENV is not set the jest CLI sets it to the value 'test'. This might be another way to check.

Solution 2

I usually have NODE_ENV=development set globally on my shell. This works for me:

typeof jest !== 'undefined'

(note that global.jest and 'jest' in global don't work, as this doesn't seem to be a global variable, just a value made available on all modules much like node's require or __filename)

Solution 3

you could add parameter to global for example global.isJest and check on the front end if it is defined

Share:
18,132
Jojo Narte
Author by

Jojo Narte

I primarily program in Swift and Java. Recently, I started learning Kotlin which is fun.

Updated on June 19, 2022

Comments

  • Jojo Narte
    Jojo Narte about 2 years

    I am creating a JS test on my react-native project. I'm specifically using firebase for react native, in which I would like to replace firebase instance with a mockfirebase instance if JS is running the code of my class.

    For example I have class setup like below.

    import firebase from 'react-native-firebase';
    class Database() {
        /// use the firebase instance
    }
    

    I'd like to have a check if jest is the running environment then I'd replace the import line with appropriate mock class.