Back

Technologies:

javascriptjavascript
avatar
Tolerim
25 days ago

How can I resolve the problem encountered while employing JEST to test mongoDB operations?

The task at hand is to write unit and integration tests but on calling the function insertOneObject, the collection is undefined and the error cannot be deciphered. The resource used is 'https://jestjs.io/fr/docs/mongodb' and 'https://github.com/shelfio/jest-mongodb'. The following code snippet is provided for reference:

export const insertOneObject = async (dbCollection, object) => {
  try {
    await db.collection(dbCollection).insertOne(object);
    console.log(`Successfully inserted object`);
  } catch (error) {
    console.error(`Failed to insert object: ${error}`);
    throw error;
  }
};

//test.js
import {
  insertOneObject,
} from "../../src/services/buildCollection.js";

describe("mongo operations", () => {
  let connection;
  let db;
  let javaMockCollection;

  beforeAll(async () => {
    connection = await MongoClient.connect(global.MONGOURI_, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    db = connection.db(globalThis.MONGODBNAME);
  });

  beforeEach(() => {
    javaMockCollection = db.collection("java-mock-collection");
  });

  afterAll(async () => {
    await connection.close();
  });

//this works
  test("should insert a doc into collection", async () => {
    const mockObj= { name: "objname" };

    await javaMockCollection.insertOne(mockObj);

    const insertedObj = await tps.findOne({ name: "objname" });
    expect(insertedObj).toEqual(mockObj);
  }); 

//this does not work
// Failed to insert object: TypeError: Cannot read properties of undefined (reading 'collection')
test("should insert a doc into collection", async () => {
    const mockObj= { name: "objname" };

    await insertOneObject("java-mock-collection", mockObj);

    const insertedObj = await tps.findOne({ name: "objname" });
    expect(insertedObj ).toEqual(mockObj);
  }); 
});
Answers(2)
avatar
Vogi
24 days ago
Verified Answer
It seems that the issue is that the db object is not being passed to the insertOneObject function. You can try passing the db object as an argument to the function like this:
export const insertOneObject = async (db, dbCollection, object) => {
  try {
    await db.collection(dbCollection).insertOne(object);
    console.log(`Successfully inserted object`);
  } catch (error) {
    console.error(`Failed to insert object: ${error}`);
    throw error;
  }
};
Then you can call the function like this:
await insertOneObject(db, "java-mock-collection", mockObj);
This should solve the issue. Let me know if you have any other questions.

Sources

db.collection.insertOne() — MongoDB ManualInsert a Document — Node.js - MongoDBIssue using JEST for mongoDB operations testingUsing with MongoDB · Jest
avatar
Tolerim
25 days ago
The reason why the collection is undefined in the insertOneObject function when called from the test is because the db parameter is not being passed to the function. In the test, the javaMockCollection is being set as db.collection("java-mock-collection") in the beforeEach function, which means that the db variable is available in the test and could be passed as the first argument to the insertOneObject function. Here's how you can modify the test to pass the db variable to insertOneObject:
test("should insert a doc into collection", async () => {
  const mockObj= { name: "objname" };

  await insertOneObject(javaMockCollection, mockObj);

  const insertedObj = await tps.findOne({ name: "objname" });
  expect(insertedObj).toEqual(mockObj);
});
In this modified test, we are passing the javaMockCollection variable (which is set to db.collection("java-mock-collection")) to the insertOneObject function instead of the name of the collection as a string. This allows the function to access the collection and insert the document as expected.
;