Getting a TypeError for constructor when mocking my database class

49 Views Asked by At

I have a simple query which uses a database wrapped in a class below. When I write the jest test I get a faiure about the database class not being a constructor. I have placed the details in code here,


                   export class ProductDb {

                    findProductById = async (productId: string) => {
                        return await ProductModel.find({ _id: productId })
                    }
                  }

                    export class ProductService {
  
                      private  db:ProductDb
   
                       constructor(){
                         this.db = new ProductDb()
                      }
                   }
     
                    processProduct = async(productId:string): Promise<any> =>{
                    const product = await this.db.findProductById(productId).then
                    /// rest of processing
                  }
  
               }

 

When I mock the database I get an error saying it is not a constructor:

TypeError: productDb_1.ProductDb is not a constructor

Here is the core piece of the test where I set up the mock for ProductDb


          const findProductByIdMock = jest.fn()

          jest.mock('../product/database/ProductDb', () =>{
           
           return {
             
               ProductDb: jest.fn().mockImplementation(() => {
               
               return {
                  findProductById: findProductByIdMock
                 }
               })
               }
           })

           describe('Product test suite', () =>{
               
               beforeEach(() =>{
                   jest.clearAllMocks()
               }
               
               it('should product with prices', async() =>{
                  const product = {
                     name: ''bananas
                  }
                  findProductByIdMock.mockResolvedValueOnce(product)
                  // rest of test
               }
           
           }

I really have no idea why I am getting this error and i have spent days trying to figure out what's going on. I would appreciate some hep in solving this issue

1

There are 1 best solutions below

1
On

According the official docs, to do a manual mock it should be:

import SoundPlayer from './sound-player';
const mockPlaySoundFile = jest.fn();
jest.mock('./sound-player', () => {
  return jest.fn().mockImplementation(() => {
    return {playSoundFile: mockPlaySoundFile};
  });
});

So the correct syntax in your case should be:

jest.mock("../product/database/ProductDb", () => {
  return jest.fn().mockImplementation(() => {
      return {
        findProductById: jest.fn(),
      };
  });
});