最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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)
发布评论

评论列表(0)

  1. 暂无评论