Jest测试NestJS StripeService时configService.get不是函数的报错
报错核心根因
你为ConfigService配置的mock实现返回了完全空的对象{},没有实现被测类依赖的get方法。StripeService构造函数执行时,尝试调用注入的configService.get('STRIPE_SECRET'),自然会触发configService.get is not a function的类型错误。同时现有mock的命名mockStripe名实不符,实际是给ConfigService做mock,容易造成逻辑混淆。
修正方案
- 替换原有的空对象mock,在ConfigService的工厂返回值中,补上StripeService实际调用的
get方法的可调用mock - 调整mock命名,匹配被mock的依赖类型,降低维护成本
修正后的完整测试代码:
import { Test, TestingModule } from '@nestjs/testing'; import { StripeService } from './stripe.service'; import { ConfigService } from '@nestjs/config'; // 匹配被mock的ConfigService实现,返回带实际用到的get方法的对象 const mockConfigService = () => ({ get: jest.fn((configKey: string) => { if (configKey === 'STRIPE_SECRET') return 'test-stripe-secret-key'; return undefined; }) }); describe('StripeService', () => { let service: StripeService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ StripeService, { provide: ConfigService, useFactory: mockConfigService } ], }).compile(); service = module.get<StripeService>(StripeService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
运行原理解释
- NestJS测试模块的依赖注入逻辑和生产环境完全一致:当在providers中配置了
{ provide: ConfigService, useFactory: mockConfigService }后,测试容器会调用这个工厂函数拿到返回值,作为ConfigService的实例注入到StripeService的构造函数参数中 - 空对象
{}在自身和原型链上都没有挂载业务方法,JS引擎执行对象方法调用时,如果找不到同名函数属性,就会抛出xxx is not a function的类型错误 - 单元测试的mock实现不需要完全复刻原类的所有方法,只需要实现被测类实际会调用到的依赖接口即可,减少不必要的测试代码冗余
内容的提问来源于stack exchange,提问作者Verdouze
相关产品推荐
相关产品推荐

