javascript - 用 Jest 测试 NestJs 服务

标签 javascript node.js unit-testing jestjs nestjs

我正在寻找一种方法来使用 Jest 测试我的 NestJs PlayerController。 我的 Controller 和服务声明:

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 can't resolve dependencies of the PlayerService (?, CommandBus, EventBus). Please make sure that the argument at index [0] is available in the PlayerService context.

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

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

最佳答案

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

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

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

参见 this answer区分单元测试和端到端测试。

参见 this answer关于如何创建模拟。

关于javascript - 用 Jest 测试 NestJs 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55567053/

相关文章:

javascript - 删除字符串之间的破折号并在 Javascript 中将字符串大写

javascript - 不调用构造函数,但调用渲染

node.js - 是否可以从 NodeJS 访问 Microsoft Dynamics NAV Web 服务?

android - 使用位置预配置 Android 模拟器?

java - 为 Spring 单元测试注入(inject)模拟 @Service

java - 模拟对象没有为我服务?

javascript - 显示阿拉伯文字

javascript - 使用 React 并使用相同组件处理不同 HTML 结构的方法

node.js - 符号链接(symbolic link) gulpfile 但获取路径符号链接(symbolic link)运行

node.js - MongoDB:带有嵌套 $group 的聚合