用Jest测试NestJs服务

我正在寻找一种用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)

有什么方法可以解决此依赖性问题?


30秒到达战场
浏览 335回答 2
2回答

达令说

因为您正在导入,所以它不起作用PlayerService。您只能导入模块,提供程序可以通过模块导入或在providers数组中声明:imports: [PlayerService, CqrsModule]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ^^^^^^^^^^^^^但是,在单元测试中,您要隔离地测试单个单元,而不是不同单元及其依存关系之间的交互。因此,比导入或声明依赖项更好的是为PlayerService或的提供程序提供模拟CqrsModule。

翻过高山走不出你

这对我有用。import { UserEntity } from './user.entity';import { TypeOrmModule } from '@nestjs/typeorm';const module = await Test.createTestingModule({&nbsp; &nbsp; controllers: [UsersController],&nbsp; &nbsp; providers: [UsersService],&nbsp; &nbsp; imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line}).compile();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript