简体   繁体   中英

Jest/Express: Tests fail with Async error only when there are multiple describe blocks

I have a Jest test file in my Express backend that works perfectly when it contains one describe() block. However, as soon as another describe block is added, I get this error regardless of how long I set the timeout:

Timeout - Async callback was not invoked within the 30000ms timeout specified by jest.setTimeout.

If I add the second describe block to a separate file, both of them run just fine and their combine run time is less than 30 seconds. But I don't see any reason to create a new file every time I want a new test suite.

Here is an extremely simplified version of both suites:

jest.setTimeout(30000);

describe('Mealplan Model Test', () => {
  beforeAll(async () => {
    await db.Connection;
  });

  afterAll(async () => {
    await mongoose.connection.close();
  });

  it('create & save mealPlan successfully', async (done) => {
    // Test logic
  });

  // You shouldn't be able to add in any field that isn't defined in the schema
  it('insert mealplan successfully, but the extra field does not persist', async (done) => {
    // test logic
  });


  // etc
});

describe('Create User recipes and foods based on admin versions', () => {
  let foodAdmin, recipeAdmin, user;
  
  beforeAll(async () => {
    await db.Connection;
  });

  afterAll(async () => {
    await mongoose.connection.close();
  });

  it('creates user recipe based on admin recipe', async () => {
    // test logic
  });

  it('returns the correct userRecipe if one already exists', async () => {
    // test logic
    
  });
  // etc
});

describe itself isn't supposed to affect how tests run, this happens because of multiple afterAll . mongoose.connection.close() closes the connection but it's not re-opened in beforeAll .

Mongoose chains connection promise for any promises it creates, this results in pending promise if a connection is never established.

If describe groups reuse the same connection, a connection should be closed only once at top level:

  beforeAll(async () => {
    await db.Connection;
  });

  afterAll(async () => {
    await mongoose.connection.close();
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM