skip to Main Content

I am trying to unit test some typescript logic with jest. I am using mongoose in order to interact with the mongo database and mongo-memory-server in order to mock mongodb.

For unclear reason, I get the following error, which seems to result from cyclic dependencies, when running the below unit test.

Error:

  ● Test suite failed to run

    RangeError: Maximum call stack size exceeded

      at Object.get [as ObjectId] (node_modules/mongoose/node_modules/mongodb/src/bson.ts:38:3)
      at Object.get [as ObjectId] (node_modules/mongoose/node_modules/mongodb/src/bson.ts:38:3)

Unit Test:

import mongoose, { Mongoose } from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";

describe("test mongo memory server", () => {
    let client: Mongoose;
    let mongod;

    beforeAll(async () => {
      mongod = await MongoMemoryServer.create();
      client = await mongoose.connect(mongod.getUri());
    });

    afterAll(async () => {

      if (mongod) {
        await mongod.stop();
      }
    });

    it("empty test", async () => {
    });
});

Used Versions in package.json:

...  "dependencies": {
        "typescript": "4.6.3",
        "mongoose": "6.2.9", // required for mongo 5.0
     },
     "devDependencies": {
        "jest": "27.5.1",
        "mongodb-memory-server": "8.4.2",
     }

P.S:

  1. When commenting out the connection to mongo (client = await mongoose.connect(mongod.getUri());), and using mongo-memory-server (version: 7.6.3) the below unit test passes. On the other hand, when the line is not commented out, it fails.
  2. When commenting out the connection to mongo (client = await mongoose.connect(mongod.getUri());), but using latest mongo-memory-server, version 8.4.2 – the test fails.

2

Answers


  1. I’ve been facing the same issue today, I just removed node_modules and package-lock.json, npm install’ed and the issue was gone.
    Take care.

    Login or Signup to reply.
  2. For me it was some errors in my jest.config.js. I had this line in it:

    moduleDirectories: ["node_modules", "src"], 
    

    When I commented it out, the error message stopped appearing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search