Cannot read property 'close' of undefined

but i can open project on localhost

I had the same problem, in the second and fourth tests in mongoclient.spec.js. The cause was the connectTimeoutMS parameter being passed to the MongoClient.connect method. I changed this

  testClient = await MongoClient.connect(
    process.env.MFLIX_DB_URI,
    { connectTimeoutMS: 200, retryWrites: true, useNewUrlParser: true },

to this

  testClient = await MongoClient.connect(
    process.env.MFLIX_DB_URI,
    { connectTimeoutMS: 1000, retryWrites: true, useNewUrlParser: true },

And it all worked.

It seems .2 of a second wasn’t long enough to wait for a connection to be established to my cluster, so MongoClient.connect wasn’t returning anything and therefore testClient was undefined, hence the error in the finally block when we try to close() testClient. Whereas allowing up to 1 second for the connection to be established was enough in my case. I guess the threshold at which it works is going to depend on a few things, including the performance of the server where the cluster is hosted, and if it’s not a locally installed cluster, speed of the network connection.

What I don’t understand is why the catch block didn’t report a test failure due to e not being null before control was passed to the finally block, as it looks like that was the intent of the code, and it would made the issue easier to debug than just seeing the error about testClient being undefined.

Welcome to the forum, hope this helps :slight_smile:

2 Likes