invernomuto
invernomuto

Reputation: 10221

Test NestJs Service with Jest

I am looking for a way to test my NestJs PlayerController with Jest. My controller and service declaration:

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) { }

My test:

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)

Any way to work around this dependency issue?

Upvotes: 3

Views: 8398

Answers (1)

Kim Kern
Kim Kern

Reputation: 60547

It does not work because you are importing PlayerService. You can only import modules, providers can be imported via a module or declared in the providers array:

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

However, in a unit test you want to test single units in isolation, not the interaction between different units and their dependencies. So better than importing or declaring your dependencies, would be providing mocks for the PlayerService or the providers of the CqrsModule.

See this answer for a distinction between unit and e2e tests.

See this answer on how to create mocks.

Upvotes: 6

Related Questions