Nest.js单元测试依赖解析失败问题求助
Nest.js单元测试依赖解析问题解决方案
问题一:UsersService测试无法解析UserRepository依赖
错误现象
运行src/users/users.service.spec.ts时,Nest无法解析UsersService的依赖UserRepository,提示该依赖需在RootTestModule上下文可用,原测试代码仅声明了UsersService作为提供者。
错误日志
FAIL src/users/users.service.spec.ts ● UsersService › should be defined Nest can't resolve dependencies of the UsersService (?). Please make sure that the argument "UserRepository" at index [0] is available in the RootTestModule context. Potential solutions: - Is RootTestModule a valid NestJS module? - If "UserRepository" is a provider, is it part of the current RootTestModule? - If "UserRepository" is exported from a separate @Module, is that module imported within RootTestModule? @Module({ imports: [ /* the Module containing "UserRepository" */ ] }) 6 | 7 | beforeEach(async () => { > 8 | const module: TestingModule = await Test.createTestingModule({ | ^ 9 | providers: [UsersService], 10 | }).compile(); 11 | at TestingInjector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:254:19) at TestingInjector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:207:33) at TestingInjector.resolveComponentInstance (../node_modules/@nestjs/testing/testing-injector.js:19:45) at resolveParam (../node_modules/@nestjs/core/injector/injector.js:128:38) at async Promise.all (index 0) at TestingInjector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:143:27) at TestingInjector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:70:13) at TestingInjector.loadProvider (../node_modules/@nestjs/core/injector/injector.js:97:9) at ../node_modules/@nestjs/core/injector/instance-loader.js:56:13 at async Promise.all (index 3) at TestingInstanceLoader.createInstancesOfProviders (../node_modules/@nestjs/core/injector/instance-loader.js:55:9) at ../node_modules/@nestjs/core/injector/instance-loader.js:40:13 at async Promise.all (index 1) at TestingInstanceLoader.createInstances (../node_modules/@nestjs/core/injector/instance-loader.js:39:9) at TestingInstanceLoader.createInstancesOfDependencies (../node_modules/@nestjs/core/injector/instance-loader.js:22:13) at TestingInstanceLoader.createInstancesOfDependencies (../node_modules/@nestjs/testing/testing-instance-loader.js:9:9) at TestingModuleBuilder.createInstancesOfDependencies (../node_modules/@nestjs/testing/testing-module.builder.js:118:9) at TestingModuleBuilder.compile (../node_modules/@nestjs/testing/testing-module.builder.js:74:9) at Object.<anonymous> (users/users.service.spec.ts:8:35)
原测试代码
import { Test, TestingModule } from '@nestjs/testing'; import { UsersService } from './users.service'; describe('UsersService', () => { let service: UsersService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [UsersService], }).compile(); service = module.get<UsersService>(UsersService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
修复方案
单元测试中需要为UsersService的依赖UserRepository提供模拟实现(或根据实际场景提供真实实例),将模拟的UserRepository添加到测试模块的提供者列表中,确保Nest能解析到该依赖。
修复后的代码
import { Test, TestingModule } from '@nestjs/testing'; import { UsersService } from './users.service'; // 根据项目实际路径调整UserRepository的导入路径 import { UserRepository } from './user.repository'; // 模拟UserRepository的核心方法,可根据测试需求扩展 const mockUserRepository = { // 示例:模拟findOne方法 findOne: jest.fn(), }; describe('UsersService', () => { let service: UsersService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ UsersService, { provide: UserRepository, useValue: mockUserRepository, }, ], }).compile(); service = module.get<UsersService>(UsersService); }); it('should be defined', () => { expect(service).toBeDefined(); }); });
问题二:UsersController测试无法解析UsersService和AuthService依赖
错误现象
运行src/users/users.controller.spec.ts时,Nest无法解析UsersController的依赖UsersService和AuthService,原测试代码仅声明了UsersController作为控制器。
错误日志
FAIL src/users/users.controller.spec.ts ● UsersController › should be defined Nest can't resolve dependencies of the UsersController (?, AuthService). Please make sure that the argument UsersService at index [0] is available in the RootTestModule context. Potential solutions: - Is RootTestModule a valid NestJS module? - If UsersService is a provider, is it part of the current RootTestModule? - If UsersService is exported from a separate @Module, is that module imported within RootTestModule? @Module({ imports: [ /* the Module containing UsersService */ ] }) 6 | 7 | beforeEach(async () => { > 8 | const module: TestingModule = await Test.createTestingModule({ | ^ 9 | controllers: [UsersController], 10 | }).compile(); 11 | at TestingInjector.lookupComponentInParentModules (../node_modules/@nestjs/core/injector/injector.js:254:19) at TestingInjector.resolveComponentInstance (../node_modules/@nestjs/core/injector/injector.js:207:33) at TestingInjector.resolveComponentInstance (../node_modules/@nestjs/testing/testing-injector.js:19:45) at resolveParam (../node_modules/@nestjs/core/injector/injector.js:128:38) at async Promise.all (index 0) at TestingInjector.resolveConstructorParams (../node_modules/@nestjs/core/injector/injector.js:143:27) at TestingInjector.loadInstance (../node_modules/@nestjs/core/injector/injector.js:70:13) at TestingInjector.loadController (../node_modules/@nestjs/core/injector/injector.js:88:9) at ../node_modules/@nestjs/core/injector/instance-loader.js:68:13 at async Promise.all (index 0) at TestingInstanceLoader.createInstancesOfControllers (../node_modules/@nestjs/core/injector/instance-loader.js:67:9) at ../node_modules/@nestjs/core/injector/instance-loader.js:42:13 at async Promise.all (index 1) at TestingInstanceLoader.createInstances (../node_modules/@nestjs/core/injector/instance-loader.js:39:9) at TestingInstanceLoader.createInstancesOfDependencies (../node_modules/@nestjs/core/injector/instance-loader.js:22:13) at TestingInstanceLoader.createInstancesOfDependencies (../node_modules/@nestjs/testing/testing-instance-loader.js:9:9) at TestingModuleBuilder.createInstancesOfDependencies (../node_modules/@nestjs/testing/testing-module.builder.js:118:9) at TestingModuleBuilder.compile (../node_modules/@nestjs/testing/testing-module.builder.js:74:9) at Object.<anonymous> (users/users.controller.spec.ts:8:35)
原测试代码(注:原粘贴代码有误,以下为对应UsersController的正确原代码结构)
import { Test, TestingModule } from '@nestjs/testing'; import { UsersController } from './users.controller'; describe('UsersController', () => { let controller: UsersController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [UsersController], }).compile(); controller = module.get<UsersController>(UsersController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
修复方案
需要为UsersController的两个依赖UsersService和AuthService提供模拟实现,将这两个模拟提供者添加到测试模块中,确保Nest能解析到所需依赖。
修复后的代码
import { Test, TestingModule } from '@nestjs/testing'; import { UsersController } from './users.controller'; import { UsersService } from './users.service'; // 根据项目实际路径调整AuthService的导入路径 import { AuthService } from '../auth/auth.service'; // 模拟UsersService,可根据测试需求扩展方法 const mockUsersService = { findUserById: jest.fn(), }; // 模拟AuthService,可根据测试需求扩展方法 const mockAuthService = { validateUser: jest.fn(), }; describe('UsersController', () => { let controller: UsersController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ controllers: [UsersController], providers: [ { provide: UsersService, useValue: mockUsersService, }, { provide: AuthService, useValue: mockAuthService, }, ], }).compile(); controller = module.get<UsersController>(UsersController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); });
内容的提问来源于stack exchange,提问作者Finddd out
相关产品推荐
相关产品推荐

