使用Jest模拟数据库类时触发TypeError:类不是构造函数
解决Jest测试中
TypeError: productDb_1.ProductDb is not a constructor的问题 问题原因分析
这个错误核心是Jest对ProductDb类的模拟没有匹配模块导出结构,或者模拟的构造函数不符合实例化要求,导致代码无法正常调用new ProductDb()。
解决方案
1. 确认模块导入路径正确性
先检查jest.mock中的路径../product/database/ProductDb是否和实际文件位置完全一致,路径错误会导致Jest无法正确定位并模拟目标模块。
2. 修正类的模拟写法
针对命名导出的ProductDb类,调整Jest模拟结构,确保ProductDb是可被new调用的构造函数,且返回包含findProductById方法的实例:
const findProductByIdMock = jest.fn(); // 修正后的mock逻辑 jest.mock('../product/database/ProductDb', () => ({ ProductDb: jest.fn(() => ({ findProductById: findProductByIdMock })) })); describe('Product test suite', () =>{ beforeEach(() =>{ jest.clearAllMocks(); }); it('should process product with prices', async() =>{ const product = { name: 'bananas' }; findProductByIdMock.mockResolvedValueOnce(product); // 实例化服务并执行测试逻辑 const service = new ProductService(); const result = await service.processProduct('test-id'); // 验证mock调用 expect(findProductByIdMock).toHaveBeenCalledWith('test-id'); // 其他业务断言 }); });
3. 修复业务代码语法错误
你的ProductService中有一处语法问题,会影响后续逻辑:
// 错误写法 const product = await this.db.findProductById(productId).then // 修正为 const product = await this.db.findProductById(productId);
多余的.then会让product变成函数而非预期的产品数据,可能间接引发测试异常。
4. TypeScript环境额外排查(若适用)
如果项目使用TypeScript,确保jest.config.js中ts-jest配置正确,支持模块导出处理:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', moduleFileExtensions: ['ts', 'js'], };
内容的提问来源于stack exchange,提问作者BreenDeen
相关产品推荐
相关产品推荐

