Home > Net >  I use NestJS with RolesGuard added to a vehicle controller, however I get a dependency error on jwt
I use NestJS with RolesGuard added to a vehicle controller, however I get a dependency error on jwt

Time:01-04

JwtStrategy

import { Injectable, Logger, UnauthorizedException } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { ConfigService } from '@nestjs/config'

import { Request } from 'express'
import { ExtractJwt, Strategy } from 'passport-jwt'
import { AuthService } from '../auth.service'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  private readonly logger = new Logger(JwtStrategy.name)

  constructor(private authService: AuthService, private readonly configService: ConfigService) {
    super({
      ignoreExpiration: false,
      secretOrKey: configService.get('JWT_SECRET'),
     
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request: Request) => {
          const data = request?.cookies['authCookie']
          if (!data) {
            return null
          }
          return data.accessToken
        },
      ]),
    })
    this.logger
  }

  async validate(payload: any) {
   // the validation code
}

AuthModule

import { Module } from '@nestjs/common'
import { MongooseModule } from '@nestjs/mongoose'
import { JwtModule } from '@nestjs/jwt'
import { PassportModule } from '@nestjs/passport'
import { ConfigModule, ConfigService } from '@nestjs/config'

import { JwtStrategy } from './strategies/jwt.strategy'
import { LocalStrategy } from './strategies/local.strategy'
import { RefreshStrategy } from './strategies/refresh.strategy'

import { User, UserSchema } from './schemas/user.schema'
import { AuthController } from './auth.controller'
import { AuthService } from './auth.service'
import { RolesGuard } from './guards/roles.guard'

@Module({
  imports: [
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
    PassportModule.register({
     
      session: false,
    }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        secret: configService.get('JWT_SECRET'),
        signOptions: {
          expiresIn:
            configService.get('NODE_ENV') === 'development'
              ? configService.get('JWT_MAX_EXPIRATION_DAYS')
              : configService.get('JWT_EXPIRES_IN'),
        },
      }),
      inject: [ConfigService],
    }),
  ],

  providers: [AuthService, LocalStrategy, JwtStrategy, RefreshStrategy, RolesGuard],
  controllers: [AuthController],
  exports: [AuthService],
})
export class AuthModule {}

VehicleModule

import { Module } from '@nestjs/common'
import { VehicleService } from './vehicle.service'
import { VehicleController } from './vehicle.controller'
import { Vehicle} from './schemas/vehicle.schema'
import { MongooseModule } from '@nestjs/mongoose'
import { AuthModule } from '../auth/auth.module'

@Module({
  imports: [
    AuthModule,
    MongooseModule.forFeature([{ name: Vehicle.name, schema: VehicleSchema }]),
  ],
  controllers: [VehicleController],
  providers: [VehicleService],
})
export class VehicleModule {}

VehicleController test file

describe('Vehicle Controller:', () => {
  let controller: VehicleController
  let service: VehicleService

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [AuthModule],
      controllers: [VehicleController],
      providers: [VehicleService],
    }).compile()

    controller = module.get<VehicleController>(VehicleController)
    service = module.get<VehicleService>(VehicleService)

    jest.clearAllMocks()
  })

I keep getting this error when I run the unit test code for vehicle controller

Nest can't resolve dependencies of the JwtStrategy (AuthService, ?). Please make sure that the argument ConfigService at index [1] is available in the AuthModule context. Potential solutions: - If ConfigService is a provider, is it part of the current AuthModule? - If ConfigService is exported from a separate @Module, is that module imported within AuthModule? @Module({ imports: [ / the Module containing ConfigService / ] })

I know it has to do with the dependency, but I could not figure out the solution.

Any help/suggestion for what could be the cause is really appreciated.

UPDATE: adding this inside AuthModule:

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
      isGlobal: true,
    }),

...

returns this error:

Nest can't resolve dependencies of the UserModel (?). Please make sure that the argument DatabaseConnection at index [0] is available in the MongooseModule context. Potential solutions:...

CodePudding user response:

 beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [],
      controllers: [VehicleController],
      providers: [
        VehicleService,
        {
          provide: AuthService,
          useValue: {
            get: jest.fn(() => MockedAuthService),
          },
        },
      ],
    }).compile()
  •  Tags:  
  • Related