Mongodb-memory-server: MongoError differ between mongodb-memory-server and vanilla mongod

Created on 18 Sep 2018  路  5Comments  路  Source: nodkz/mongodb-memory-server

First off, I totally love mongodb-memory-server - it makes testing models and GraphQL APIs a breeze!

If I log the errmsg prop of a MongoError like this:

try {
  await col.insertOne(doc);
} catch (error) {
  if (error typeof MongoError && error.code === 11000) {
    console.log(error.errmsg);
  }
}

I get this with mongodb-memory-server (Jest):

E11000 duplicate key error dup key: { : "YF2dqu11Z9mj", : "test" }

And this with a vanilla mongod process (Node):

E11000 duplicate key error collection: myDatabase.myCollection index: organizationId_1_name_1 dup key: { : "YF2dqu11Z9mj", : "test" }

I parse errmsg to figure out which index clashed so I can provide a more detailed error message to the client. But since the index part of errmsg is not available in the MongoError from mongodb-memory-server I can't write any tests for it.

Is there any way around this? Could it be that Jest is the reason for this?

All 5 comments

I think that this difference in error messages depends on mongodb version.

If your testing and production versions of mongodb are the same, then you need to try make storageEngine the same. By default it is in memory.

So if it helps, please put here your solution for future googlers.

PS. You may spin app for some tests regular mongo instance, but for other tests - default in memory for spead.

Ok, cool! I have the same version but not the same engine. I'm going to try that. Keep you posted.

Confirming that changing the engine to wiredTiger (same as for production) gives the correct errmsg.

new MongodbMemoryServer({
  binary: {
    version: '4.0.2',
  },
  instance: {
    // Available engines:
    // storageEngines: [ 'devnull', 'ephemeralForTest', 'mmapv1', 'wiredTiger' ],
    storageEngine: 'wiredTiger',
  },
});

For future googlers:

I've published a package that enables you to set the storage engine per test file in Jest. It also enables you to keep a single mongodb-memory-server server running between tests when you run Jest in watch mode, and other good stuff.

https://www.npmjs.com/package/jest-environment-mongodb (docs here)
https://www.npmjs.com/package/jest-environment-mongodb-wiredtiger
https://www.npmjs.com/package/jest-environment-mongodb-ephemeral

@lirbank wow great!

Please open Pull Request for README.md - add links to your packages under Jest section.
Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

nguyenhoangvi000 picture nguyenhoangvi000  路  5Comments

rhinoman picture rhinoman  路  11Comments

mathieug picture mathieug  路  11Comments

maxpeterson picture maxpeterson  路  11Comments

EnergeticPixels picture EnergeticPixels  路  3Comments