Jest.js 当模拟我的数据库类时,为构造函数获取TypeError

xqnpmsa8  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(130)

我有一个简单的查询,它使用了一个 Package 在下面类中的数据库。当我写jest测试时,我得到了一个关于数据库类不是构造函数的错误。我把细节用代码写在这里,

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
                  }
  
               }

当我模拟数据库时,我得到一个错误,说它不是一个构造函数:

TypeError: productDb_1.ProductDb is not a constructor

下面是我为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
               }
           
           }

我真的不知道为什么我得到这个错误,我花了几天时间试图弄清楚发生了什么事。我将感激一些帮助在解决这个问题

zwghvu4y

zwghvu4y1#

根据官方文档,要进行手动模拟,应该是:

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

因此,在您的情况下,正确的语法应该是:

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

相关问题