Search code examples
jestjsts-jest

How to exit from jest test on some conditions check in beforeAll?


I using Jest to run tests. I am starting a test server which uses tests table to do data insertion and read. So what I am trying to achive is first check in the beforeAll if the running environment is test or not as when I will deploy on server so that it won't run tests in the production db if some mistakes are there and the sever is not test server. So for this I have a an endpoint which gives the environment and I want to call that endpoint in beforeAll and then if the environment is test continue and execute the test cases other wise I don't want to run the test cases. How can I acvieve this in Jest? Below is the code I want to run but return or throw or process.exit nothing is exiting the test cases and all of the tests runs.

beforeAll(async () => {
  const GET_ENVIRONMENT_QUERY = gql`
    query GetEnvironment {
      getEnvironment
    }
  `;
  const loggedInClient = createApolloClientInstance("LOGGEDIN");
  const response = await loggedInClient.query({
    query: GET_ENVIRONMENT_QUERY,
  });
  if (response.data.getEnvironment !== "TEST_") {
    console.log("Here it should exit");
    return;
  }
});

Solution

  • If I'm right in thinking that you only want to run your tests when the environment is 'test', then this sounds like something you could accomplish in a setup file.

    You configure this in your jest.config file as follows:

    {
        ...,
        globalSetup: `path/to/your/setup.js/file`,
        ...
    }
    

    See more information about this in the jest docs.

    Transfer the beforeAll code to this file, which will be run before any tests are run. Then in your setup.js file you can simply process.exit(1) (with a helpful message to the user perhaps) if the environment is not what you intend to be.

    I would add, by the way, that you really should run tests in all environments - probably what you need instead of your current setup is a stub of your DB and other services that is used for testing purposes, but that is a separate issue.