here is how i connect all this stuff for test
const mockAdminGuard = {
canActivate: jest.fn(() => true),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [
{
provide: UsersService,
useValue: mockUsersService,
},
{
provide: AdminGuard,
useValue: mockAdminGuard,
},
],
}).compile();
here is test which is not mocking guard
describe('getUsers', () => {
it('should return error when request is not from admin', async () => {
mockAdminGuard.canActivate.mockImplementationOnce(() => false);
const response = await userController.getUsers();
console.log(response);
expect(response).toBe(12312321);
});
});
here is controller
@UseGuards(AdminGuard)
@Get()
async getUsers(): Promise<User[]> {
return await this.usersService.findAll();
}
here is admin guard
@Injectable()
export class AdminGuard implements CanActivate {
constructor(private reflector: Reflector) {}
async canActivate(
context: ExecutionContext,
): Promise<boolean> {
const request = context.switchToHttp().getRequest();
const user = await User.findOne({where: { id: request.user.sub}});
// Return a boolean indicating if the user has the 'admin' role
return user && user.role === 'admin';
}
}
everything works fine for requests, but i cant figure out how to write test for this one