90

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.

4 Answers 4

169

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.

Sign up to request clarification or add additional context in comments.

4 Comments

JEST_WORKER_ID wasn't set for me, but NODE_ENV was.
If you you Next.js's export feature JEST_WORKER_ID will defined in production too since it seems to use jest-worker module for it.
Why do you want to evaluate it each time if it never changes? Better to store it in a const.
I do this process.env.JEST_WORKER_ID === undefined || process.env.NODE_ENV !== 'test'
25

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)

1 Comment

In my React Native setup, typeof jest !== 'undefined' is false (i.e. it is defined) when running in the iOS simulator, attached to the debugger, so I had to check the worker ID as shown in the other answer.
2

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

Comments

1

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

3 Comments

It doesn't work from a type-checking perspective. TS complains about the includes method because expectations are different since the left is a combination of [string and number], but the other side is globally considered a string.
So you decided to give me a minus. Cool
@Masoud you can change the 0 number to a string: '0'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.