node.js - Why is my JEST mockResolvedValueOnce not working? - Stack Overflow

I have this function:export const insertOne = async (table, data) => {try {const client = await get

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')

Share Improve this question edited Nov 22, 2024 at 2:38 Phil 165k25 gold badges262 silver badges267 bronze badges asked Nov 21, 2024 at 0:10 CarlosCarlos 571 silver badge16 bronze badges 3
  • const db = client.db(process.env.MONGO_DATABASE)

    发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742321408a4421885.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信