Jest | test.each table | How to configure the test.each table with variables defined in beforeAll function

Viewed 892

How can I interpolate the test.each table with variables defined elsewhere? In the following example I am trying to use someData defined in beforeAll. Here's the Jest functionality I am using: https://jestjs.io/docs/api#testeachtablename-fn-timeout

Follows a code snippet of what I am trying to do:

const someCall = async () => {
  return { field: "lalala" };
};

describe(`Some test suite`, () => {
  let someData;

  beforeAll(async () => {
    const callOutput = await someCall();
    someData = callOutput.field;
  });

  beforeEach(async () => {});

  it.each`
    data                | moreData
    ${{ name: "Jack" }} | ${"foo"}
    ${someData}         | ${"bar"}
  `("Tests here...", async ({ data, moreData }) => {
    console.log("Data:", data);                // <---- data is undefined for the second test
    console.log("More data:", moreData);
  });
});

The issue is that in the second test someData is undefined rather than having the value "lalala".

1 Answers

From the doc Defining Tests says:

Tests must be defined synchronously for Jest to be able to collect your tests.

Note: This means when you are using test.each you cannot set the table asynchronously within a beforeEach / beforeAll.

Suggestion: You should prepare the test data before defining the test suites and test cases. Generate a data.json file use Node.js script or shell script, etc... Require and use the data.json file from your test file before running the npm test script.

Related