Skip to content

missing injection token in createTestingModule causes undefined controller dependencies #15836

@mnalsup

Description

@mnalsup

Is there an existing issue for this?

  • I have searched the existing issues

Current behavior

When a Controller depends on a Decorator with a Pipe that requires REQUEST to be Injected, and the testing module does not include a provider for REQUEST it runs the tests with the controller's dependencies as undefined. For Instance:

    const module: TestingModule = await Test.createTestingModule({
      controllers: [MyController],
      providers: [
        {
          provide: LoggerService,
          useValue: {
            assign: jest.fn(),
            log: jest.fn(),
          },
        },
        // We provide the pipe, but...
        GetUserPipe,
        // MISSING: REQUEST provider that GetUserPipe needs via @Inject(REQUEST)!
        // Without REQUEST, the pipe constructor gets 'undefined' for this.req
      ],
    }).compile();
@Controller('api')
export class MyController {
  constructor(private readonly logger: LoggerService) {}

  @Get('data')
  async getData(@User() user: UserDto): Promise<any> {
    // This line will show in the error, making it seem like the issue is here
    this.logger.assign({ userId: user.id, userName: user.name });
    
    return { message: `Hello user ${user.id}` };
  }
}

Will result in the following error.

    TypeError: Cannot read properties of undefined (reading 'assign')

      15 |   async getData(@User() user: UserDto): Promise<any> {
      16 |     // This line will show in the error, making it seem like the issue is here
    > 17 |     this.logger.assign({ userId: user.id, userName: user.name });
         |                 ^
      18 |     
      19 |     return { message: `Hello user ${user.id}` };
      20 |   }

      at MyController.getData (my.controller.ts:17:17)
      at Object.<anonymous> (my.controller.spec.ts:44:22)

As you can see the logger is undefined which was provided properly.

Minimum reproduction code

https://github.com/mnalsup/reproduce-undefined-injects

Steps to reproduce

git clone https://github.com/mnalsup/reproduce-undefined-injects.git
cd reproduce-undefined-injects
npm install
npm test

Expected behavior

What I would expect is the standard nestjs error that describes that a dependency was unable to be resolved like:
"Nest can't resolve dependencies of the GetUserPipe (?). Please make sure that the argument REQUEST at index [0] is available in the RootTestModule context."

I would also expect that unrelated depenencies would still be resolved like the this.logger in the example.

NestJS version

No response

Packages versions

    "@nestjs/common": "^11.0.0",
    "@nestjs/core": "^11.0.0",
    "@nestjs/testing": "^11.0.0",

Node.js version

v20.19.0

In which operating systems have you tested?

  • macOS
  • Windows
  • Linux

Other

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions