Skip to content
Advertisement

Jest: shared async code between test blocks

I have some test code like this:

test('Test', async () => {
  const someData = await setup()
  const actual = myFunc(someData.x)
  expect(actual.a).toEqual(someData.y)
  expect(actual.b).toEqual(someData.y)
  ... many more like this
}

I would like to break apart the code into multiple test blocks (because I can’t even add a description message to each expect statement).

If Jest supported async describe, I could do this:

describe('Some group of tests', async () => {
const someData = await setup()

test('Test1', async () => {
  const actual = myFunc(someData.x)
  expect(actual.a).toEqual(someData.y)
}

test('Test2', async () => {
  const actual = myFunc(someData.x)
  expect(actual.b).toEqual(someData.y)
}
})

I could duplicate the setup call for each test of course, but that would slow down the test considerable (I’m populating MongoDB there).

So, any way I can improve the structure of my test with Jest?

Advertisement

Answer

It’s correct that describe callback function isn’t supposed to be asynchronous. It synchronously defines tests for a suite, any asynchronous operations in its scope will be discarded.

Previously Jasmine and Jest allowed to access common test context with regular functions and this. This feature was deprecated in Jest; common variables need to be user-defined.

Shared code can be moved into helper function that internally uses beforeAll, beforeEach, etc:

const setupWithTestContext = (testContext = {}) => {
  beforeAll(async () => {
    const setupData = await setup();
    Object.assign(testContext, setupData);
  });
  return testContext; // sets up a new one or returns an existing
});

const anotherSetupWithTestContext = (testContext = {}) => {
  beforeEach(() => {
    testContext.foo = 0;
  });
  return testContext;
});

...

describe('Some group of tests', async () => {
    const sharedTestData = setupTestContext();
    // or
    // const sharedTestData = {}; setupTestContext(sharedTestData);

    anotherSetupWithTestContext(sharedTestData);

    test('Test1', async () => {
      // context is filled with data at this point
      const actual = myFunc(sharedTestData.x)
      ...
    }
    ...
})
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement