Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
      ...
    }
    ...
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...