I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controllers allows me to retrieve the user object associated with the token.
Here's how I use the decorator:
import {
Body,
Controller,
Post,
UseGuards,
UsePipes,
ValidationPipe,
} from '@nestjs/common'
import { LogbooksService } from './logbooks.service'
import { User } from 'src/typeorm/user.entity'
import { AuthUser } from 'src/users/users.decorator'
import { UsersGuard } from 'src/users/users.guard'
import { CreateLogbookDto } from './dto/CreateLogbook.dto'
@Controller('logbooks')
export class LogbooksController {
constructor(private readonly logbookService: LogbooksService) {}
@Post()
@UseGuards(UsersGuard)
@UsePipes(ValidationPipe)
async createLogbook(
@Body() createLogbookDto: CreateLogbookDto,
@AuthUser('user') user: User,
) {
const newLogbook = await this.logbookService.createLogbook(
createLogbookDto,
user,
)
return newLogbook
}
}
Below is the simple decorator code:
import { createParamDecorator } from '@nestjs/common'
export const AuthUser = createParamDecorator((data: string, req) => {
return req.args[0].principal
})
The version of Nest being used is 10.2.1
Any advice on how to successfully do this would be greatly appreciated. Thank you!