How to determine if JEST is running the code or no

2019-06-16 01:18发布

问题:

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.

回答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.