I have this function:
export const insertOne = async (table, data) => {
try {
const client = await getClient();
const db = client.db(process.env.MONGO_DATABASE);
const collection = db.collection(table);
const { insertedId } = await collection.insertOne({
...data,
createdAt: moment().tz("America/Mexico_City").toISOString(),
updatedAt: moment().tz("America/Mexico_City").toISOString(),
});
const insertedData = await collection.findOne({ _id: insertedId });
return insertedData;
} catch (error) {
mwLogger('error', 'Error inserting one to the database :', {
name: error?.name || 'Unknown Error',
message: error?.message || 'No message provided',
code: error?.code || 'No error code',
stack: error?.stack || 'No stack trace available'
});
throw new Error('Database insertion failed');
}
}
It works as expected with database connection strings, table and the collection. But When I try to do a JEST Test of it I have one issue. This is my test file so I can clarify:
describe('insertOne', () => {
beforeEach(() => {
// Mock db and collection setup
mockDb = { collection: jest.fn() };
mockCollection = { insertOne: jest.fn(), findOne: jest.fn() };
mockClient = { db: jest.fn().mockReturnValue(mockDb) };
// Mock MongoClient.connect to return mockClient
MongoClient.connect.mockResolvedValue(mockClient);
// Mock collection method to return mockCollection
mockDb.collection.mockReturnValue(mockCollection);
});
it('should insert data correctly and return the inserted document', async () => {
const mockData = { name: 'John Doe' };
// Mock the insertOne method to resolve with insertedId
const insertedId = '123';
mockCollection.insertOne.mockResolvedValueOnce({ insertedId });
// Mock findOne to return the inserted data with timestamps
const mockInsertedData = {
_id: insertedId,
...mockData,
createdAt: expect.any(String),
updatedAt: expect.any(String),
};
mockCollection.findOne.mockResolvedValueOnce(mockInsertedData);
const result = await insertOne('users', mockData);
// Assertions
expect(mockCollection.insertOne).toHaveBeenCalledWith(
expect.objectContaining({
...mockData,
createdAt: expect.any(String),
updatedAt: expect.any(String),
})
);
expect(result).toEqual(mockInsertedData);
});
});
The piece of code of the test file mockCollection.insertOne.mockResolvedValueOnce({ insertedId });
is not mocking the result I want out of that test. Which is the await collection.insertOne
of the source file.
What would the correct approach be to mock that specific piece of code?
The error im getting is TypeError: Cannot read properties of undefined (reading 'insertedId')
I have this function:
export const insertOne = async (table, data) => {
try {
const client = await getClient();
const db = client.db(process.env.MONGO_DATABASE);
const collection = db.collection(table);
const { insertedId } = await collection.insertOne({
...data,
createdAt: moment().tz("America/Mexico_City").toISOString(),
updatedAt: moment().tz("America/Mexico_City").toISOString(),
});
const insertedData = await collection.findOne({ _id: insertedId });
return insertedData;
} catch (error) {
mwLogger('error', 'Error inserting one to the database :', {
name: error?.name || 'Unknown Error',
message: error?.message || 'No message provided',
code: error?.code || 'No error code',
stack: error?.stack || 'No stack trace available'
});
throw new Error('Database insertion failed');
}
}
It works as expected with database connection strings, table and the collection. But When I try to do a JEST Test of it I have one issue. This is my test file so I can clarify:
describe('insertOne', () => {
beforeEach(() => {
// Mock db and collection setup
mockDb = { collection: jest.fn() };
mockCollection = { insertOne: jest.fn(), findOne: jest.fn() };
mockClient = { db: jest.fn().mockReturnValue(mockDb) };
// Mock MongoClient.connect to return mockClient
MongoClient.connect.mockResolvedValue(mockClient);
// Mock collection method to return mockCollection
mockDb.collection.mockReturnValue(mockCollection);
});
it('should insert data correctly and return the inserted document', async () => {
const mockData = { name: 'John Doe' };
// Mock the insertOne method to resolve with insertedId
const insertedId = '123';
mockCollection.insertOne.mockResolvedValueOnce({ insertedId });
// Mock findOne to return the inserted data with timestamps
const mockInsertedData = {
_id: insertedId,
...mockData,
createdAt: expect.any(String),
updatedAt: expect.any(String),
};
mockCollection.findOne.mockResolvedValueOnce(mockInsertedData);
const result = await insertOne('users', mockData);
// Assertions
expect(mockCollection.insertOne).toHaveBeenCalledWith(
expect.objectContaining({
...mockData,
createdAt: expect.any(String),
updatedAt: expect.any(String),
})
);
expect(result).toEqual(mockInsertedData);
});
});
The piece of code of the test file mockCollection.insertOne.mockResolvedValueOnce({ insertedId });
is not mocking the result I want out of that test. Which is the await collection.insertOne
of the source file.
What would the correct approach be to mock that specific piece of code?
The error im getting is TypeError: Cannot read properties of undefined (reading 'insertedId')
const db = client.db(process.env.MONGO_DATABASE)