我正在寻找一种用Jest测试我的NestJs PlayerController的方法。我的控制器和服务声明:import { QueryBus, CommandBus, EventBus } from '@nestjs/cqrs';/** * The service assigned to query the database by means of commands */@Injectable()export class PlayerService { /** * Ctor * @param queryBus */ constructor( private readonly queryBus: QueryBus, private readonly commandBus: CommandBus, private readonly eventBus: EventBus ) { }@Controller('player')@ApiUseTags('player')export class PlayerController { /** * Ctor * @param playerService */ constructor(private readonly playerService: PlayerService) { }我的测试:describe('Player Controller', () => { let controller: PlayerController; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [PlayerService, CqrsModule], controllers: [PlayerController], providers: [ PlayerService, ], }).compile(); controller = module.get<PlayerController>(PlayerController); }); it('should be defined', () => { expect(controller).toBeDefined(); });...Nest无法解析PlayerService的依赖项(?,CommandBus,EventBus)。请确保在PlayerService上下文中索引[0]处的参数可用。 at Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)有什么方法可以解决此依赖性问题?
2 回答
达令说
TA贡献1821条经验 获得超6个赞
因为您正在导入,所以它不起作用PlayerService。您只能导入模块,提供程序可以通过模块导入或在providers数组中声明:
imports: [PlayerService, CqrsModule]
^^^^^^^^^^^^^
但是,在单元测试中,您要隔离地测试单个单元,而不是不同单元及其依存关系之间的交互。因此,比导入或声明依赖项更好的是为PlayerService或的提供程序提供模拟CqrsModule。
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
这对我有用。
import { UserEntity } from './user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
const module = await Test.createTestingModule({
controllers: [UsersController],
providers: [UsersService],
imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line
}).compile();
添加回答
举报
0/150
提交
取消