title: Mock mongoose aggregate function in jest
body: <p>I have a middleware as below, for which I am trying to do unit testing using jest,</p>
  <p><strong>Middleware:</strong></p>
  <pre><code>import Ph from './Ph.model';
  fAP = (req, res, next) =&gt; {
          const pN = req.body.pN;
          
          if (pN != null) {
  
              Ph.aggregate([
                  { $match: { 'polNum': { $eq: pN } } },
                  {
                      $match: {
                          $expr:
                          {
                              $and: [
                                  { $eq: ['$pCS', 'A'] }
                              ]
                          }
                      }
                  }
              ]).exec((err, data) =&gt; {
  
                  if (data.length &gt; 0) {
                      req.p = data[0];
                      req.body.pN = data[0].pN;
                      return next();
                  } else {
                      return res.json({ message: 'Not found'});
                  }
  
              });
          } else {
              return res.json({ message: 'Cannot be null.'});
          }
      }
  </code></pre>
  <p><strong>Test code:</strong></p>
  <pre><code>import { Request, Response, NextFunction } from 'express';
  
  import PhCtrl from 'Ph.controller';
  const PhController = new PhCtrl();
  
  import Ph from './Ph.model';
  
  describe('PhController', () =&gt; {
    let mockRequest: any;
    let mockResponse: any;
    let mockNext: NextFunction = jest.fn();
  
    beforeEach(() =&gt; {
      mockRequest = {
        body: {
          polNum: ''
        }
      };
      mockResponse = {
        json: jest.fn()
      };
    });
  
    // fAP middleware
    describe('fAP middleware', () =&gt; {
      // pN is not null and matches
      describe('when pn is not null', () =&gt; {
        // found
        test('should call next when matches', async () =&gt; {
          const mockRequest: any = {
            body: {
              pN: '3028'
            }
          };
          const mockResponse: any = {
            json: jest.fn()
          };
          const mockNext: NextFunction = jest.fn();
  
          const responseData = require('../../../mock-data/p.json');
          
          Ph.aggregate = jest.fn().mockImplementationOnce(() =&gt; ({
            exec: jest.fn().mockResolvedValueOnce(responseData)
          }));
  
          await PhController.fAP(
            mockRequest,
            mockResponse,
            mockNext
          );
          expect(mockNext).toHaveBeenCalled();
        });
      });
    });
  });
  
  </code></pre>
  <p><strong>Error:</strong>
  But I am receiving the following error, when I try to mock aggregate function.
  In case of findOne, the similar process works, but fail in aggregation method of mongoose. Any help will be appreciated.</p>
  <blockquote>
  <p>● PhController › fAP middleware › when
  pn is not null › should call next when matches</p>
  <pre><code>expect(jest.fn()).toHaveBeenCalled()
  
  Expected number of calls: &gt;= 1
  Received number of calls:    0
  
    54 |           mockNext
    55 |         );
  &gt; 56 |         expect(mockNext).toHaveBeenCalled();
       |                          ^
    57 |       });
    58 | 
    59 |       // active ph is not found
  
    at tests/server/api/ph/ph.controller.test.ts:56:26
  </code></pre>
  </blockquote>