Issue
I've got a controller configured in NestJS and I want to check that the appropriate guards are set - does anyone have an example of how it could be done?
This (abridged) example works correctly as an application so I'm only after guidance on testing.
You'll notice in the user test there are tests where I'm calling Reflect.getMetadata
. I'm after something like this - when I check it on the __guards__
metadata, this is a function and I'm struggling to mock it out so I can check that it's applied with AuthGuard('jwt')
as it's setting.
User.controller.ts
@Controller('/api/user')
export class UserController {
@UseGuards(AuthGuard('jwt'))
@Get()
user(@Request() req) {
return req.user;
}
}
User.controller.spec.ts
describe('User Controller', () => {
// beforeEach setup as per the cli generator
describe('#user', () => {
beforeEach(() => {
// This is how I'm checking the @Get() decorator is applied correctly - I'm after something for __guards__
expect(Reflect.getMetadata('path', controller.user)).toBe('/');
expect(Reflect.getMetadata('method', controller.user)).toBe(RequestMethod.GET);
});
it('should return the user', () => {
const req = {
user: 'userObj',
};
expect(controller.user(req)).toBe(req.user);
});
});
});
Solution
I realize its not quite the answer you are looking for, but building on @Jay McDoniel's answer I used the following to test a custom decorator's existence on a controller function (although i'm not 100% sure if this is the correct way to test this for non-custom guards)
import { Controller } from '@nestjs/common';
import { UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from './jwtAuthGuard';
@Controller()
export class MyController {
@UseGuards(JwtAuthGuard)
user() {
...
}
}
it('should ensure the JwtAuthGuard is applied to the user method', async () => {
const guards = Reflect.getMetadata('__guards__', MyController.prototype.user)
const guard = new (guards[0])
expect(guard).toBeInstanceOf(JwtAuthGuard)
});
And for controllers
it('should ensure the JwtAuthGuard is applied to the controller', async () => {
const guards = Reflect.getMetadata('__guards__', MyController)
const guard = new (guards[0])
expect(guard).toBeInstanceOf(JwtAuthGuard)
});
Answered By - myol
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.