Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 292
Jojo Narte Avatar asked Jun 20 '18 05:06

Jojo Narte


People also ask

How do I know if I have Jest?

How to check if jest is installed. In addition to that npm is creating a shortcut in you local node_modules under the directory . bin son in there you should find a link to jest.

How are Jest tests run?

Jest will execute different test files potentially in parallel, potentially in a different order from run to run. Per file, it will run all describe blocks first and then run tests in sequence, in the order it encountered them while executing the describe blocks.

How does Jest know which files to run?

Jest will look for test files with any of the following popular naming conventions: Files with . js suffix in __tests__ folders. Files with .


3 Answers

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.

like image 124
gae123 Avatar answered Oct 12 '22 19:10

gae123


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)

like image 38
Fábio Santos Avatar answered Oct 12 '22 17:10

Fábio Santos


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

like image 2
BlueStory Avatar answered Oct 12 '22 18:10

BlueStory