NestJs服务与Jest测试

问题描述 投票:1回答:1

我正在寻找一种方法来测试我的NestJs PlayerController与Jest。我的控制器和服务声明:

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)的依赖关系。请确保indexService [0]中的参数在PlayerService上下文中可用。

  at Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)

有办法解决这个依赖问题吗?

javascript node.js unit-testing jestjs nestjs
1个回答
1
投票

它不起作用,因为您正在导入PlayerService。您只能导入模块,提供程序可以通过模块导入或在providers数组中声明:

imports: [PlayerService, CqrsModule]
          ^^^^^^^^^^^^^

但是,在单元测试中,您希望单独测试单个单元,而不是不同单元之间的交互及其依赖性。因此,比导入或声明您的依赖项更好,将为PlayerServiceCqrsModule的提供者提供模拟。

有关单元和e2e测试之间的区别,请参阅this answer

有关如何创建模拟的信息,请参阅this answer

© www.soinside.com 2019 - 2024. All rights reserved.