Yaron Sternbach
Yaron Sternbach

Reputation: 101

Getting "RangeError: Maximum call stack size exceeded" when unit testing with mongodb-memory-server

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.

Upvotes: 9

Views: 3240

Answers (2)

JimmyTheCode
JimmyTheCode

Reputation: 5734

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.

Upvotes: 1

Fi Li Ppo
Fi Li Ppo

Reputation: 187

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.

Upvotes: 0

Related Questions