Test using mongodb-memory-server is failing/timing out

Viewed 546

I’m setting up mongodb-memory-server in my backend for test purposes and am experiencing some issues when running tests that I need to debug. My issue is that when I run my test (which will create a mongodb doc somewhere in the service being tested), the test times out.

As I understand it, this is because when the test is executed and a new mongo doc is trying to be created during the test, I console log mongoose.connection.readyState and it says it’s 0, meaning that mongoose is disconnected. This is strange to me because I added console logs to my connectMongoose() function (pictured below) and it says that mongoose is connected.

So my main question is why does it say mongoose is connected at the end of connectMongoose(), but it says it’s disconnected during the execution of the unit test/service function? How can I ensure that MongoDB-memory-server is fully connected prior to test execution?

Below is a screenshot showing how I am doing the mongoose test connection:

enter image description here

Below this is a screenshot of exactly where and how mongodb-memory-server is being used:

enter image description here

Here is a screenshot of my jest.config.js:

enter image description here

And finally the actual test file which has the failing test (what I’m asking about):

enter image description here

2 Answers
beforeAll(connectMongoose)
beforeEach(clearDatabase)
afterAll(disconnectMongoose)

Your three functions here are async functions, but you don't await them - is it possible that the connect Mongoose returns whilst the promise is still awaiting, and the other code continues despite the async function not having completed yet?

Perhaps this would better serve your purpose?

beforeAll(() => {
    await connectMongoose
})

Before :

beforeAll(connectMongoose)
beforeEach(clearDatabase)
afterAll(disconnectMongoose)

After:

beforeAll(async() => {await connectMongoose})
beforeEach(async() => {await clearDatabase})
afterAll(async () => { await disconnectMongoose})

The reason is you should wait until the mongoose connection is done completely and remove set timeout in connectMongoose function not needed there.If you want to use jest timeout you can use it in the beforeEach function.

Related