NestJS新手排查AuthService无signin、signup方法类型错误
问题排查:"property signin, signup does not exist on type AuthService" 错误
错误原因
你的测试代码未在测试模块中注入AuthService,但AuthController必然依赖该服务(否则不会调用它的signin/signup方法)。当测试模块仅声明控制器、未提供对应服务时,Nest无法正确实例化带有依赖的控制器,TypeScript类型检查会因无法解析AuthService的真实类型抛出该错误。
解决步骤
修改auth.controller.spec.ts的测试模块配置,将AuthService添加到提供者列表:
import { Test, TestingModule } from '@nestjs/testing'; import { AuthController } from './auth.controller'; import { AuthService } from './auth.service'; // 导入AuthService describe('AuthController', () => { let controller: AuthController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [AuthController], providers: [AuthService], // 添加该服务注入 }).compile(); controller = module.get<AuthController>(AuthController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
额外说明
如果后续需要模拟AuthService行为而非使用真实实例,可通过Nest的jest.mock或TestingModule的overrideProvider方法替换,但当前场景下直接注入真实服务即可解决类型错误。
内容的提问来源于stack exchange,提问作者umair
相关产品推荐
相关产品推荐

