【问题标题】:Test NestJs Service with Jest用 Jest 测试 NestJs 服务
【发布时间】:2019-08-29 05:26:18
【问题描述】:

我正在寻找一种方法来使用 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, 事件总线)。请确保索引 [0] 处的参数是 在 PlayerService 上下文中可用。

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

有什么方法可以解决这个依赖问题?

【问题讨论】:

    标签: javascript node.js unit-testing jestjs nestjs


    【解决方案1】:

    这对我有用。

    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();
    

    【讨论】:

    • 这与TypeORM模块无关。
    【解决方案2】:

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

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

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

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

    请参阅this answer,了解如何创建模拟。

    【讨论】:

      猜你喜欢
      • 2020-07-16
      • 2022-01-06
      • 2020-11-16
      • 2021-02-03
      • 1970-01-01
      • 2020-02-04
      • 1970-01-01
      • 2022-06-10
      • 2019-12-28
      相关资源
      最近更新 更多