0
votes

I'm trying to run some async functions before any test in a specific file is ran. I tried doing the following:

describe('api/user', () => {
    let user;
    const userObj = {...};

    beforeAll(async () => {
        user = await new User(userObj).save(); // This is a mongoose document
    });
    ...
});

Whenever I have something in the beforeAll function I get an error:

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

I tried changing the timeout time to 30 seconds and that didn't fix it. I then tried adding the done function before the end of the beforeAll function, and it didn't fix the issue either.

How can I run await in the beforeAll function?

2
Can you create a new test file and try to reproduce the problem? I believe the second argument timeout of the beforeAll function works.Duc Nguyen
Try not using async/await and instead use then and return the promiseAdrian Pascu
Your new User().save() code is probably not runs.felixmosh
What's User? Is it Mongoose or else? This needs to be specified in the question. The question doesn't make sense in general because in general it's supposed to be done like you did and it's expected to work.Estus Flask
@EstusFlask Yes, it's a mongodb docJessica

2 Answers

1
votes

That a block with async function results in test timeout even with very long timeout values means that there's pending promise that never resolves. Adding done to async functions is not a viable option because it cannot improve this but can also result in more timeouts in case done is never called.

This is a known case for Mongoose models, it's known for chaining connection promise internally. If there's no connection, model operations return pending promises.

The solution is to establish a connection before other operations. In case a connection is shared for the test suite, it should be:

beforeAll(async () => {
    await mongoose.connect(...);
    user = await new User(userObj).save();
});
0
votes

I ran into a similar problem and had to explicitly pass in and call the done function:

describe('api/user', () => {
    let user;
    const userObj = {...};

    beforeAll(async (done) => {
        user = await new User(userObj).save(); // This is a mongodb document
        done();
    });
    ...
});