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

JavascriptFirebaseReact NativeMockingJestjs

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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

Solution 4 - Javascript

For me best way is checking two things - 0 and undefined:

[0, undefined].includes(process.env.JEST_WORKER_ID)

so it's based on https://stackoverflow.com/a/52231746/3012785

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJojo NarteView Question on Stackoverflow
Solution 1 - Javascriptgae123View Answer on Stackoverflow
Solution 2 - JavascriptFábio SantosView Answer on Stackoverflow
Solution 3 - JavascriptBlueStoryView Answer on Stackoverflow
Solution 4 - JavascriptDarex1991View Answer on Stackoverflow