Tags down


How can I test a controller with more than one guard on NestJS

By : Henk
Date : September 13 2020, 05:00 PM
I think the issue was by ths following , You need to specify each guard you are wanting to override with its own overrideGuard. You can have a beforeEach that looks like this:
code :
beforeEach(async () => {
  const moduleFixture: TestingModule = await Test.createTestingModule({
    imports: [AppModule],
    .useValue({ canActivate: () => true })
    .useValue({ canActivate: () => true })

  app = moduleFixture.createNestApplication();
  await app.init();

Share : facebook icon twitter icon

Apply one Guard to multiple routes in Nestjs

By : jekeel
Date : March 29 2020, 07:55 AM
I hope this helps . You have three possible solutions to set guard:
apply to method (your example) apply to controller apply globally
code :
export class CatsController {}
const app = await NestFactory.create(ApplicationModule);
app.useGlobalGuards(new RolesGuard());

Nestjs unit-test - mock method guard

By : user2697468
Date : March 29 2020, 07:55 AM
This might help you I have started to work with NestJS and have a question about mocking guards for unit-test. I'm trying to test a basic HTTP controller that has a method Guard attach to it. , There are 3 issues with the example repo provided:
code :
import { CanActivate } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ForceFailGuard } from './force-fail.guard';

describe('AppController', () => {
  let appController: AppController;

  beforeEach(async () => {
    const mock_ForceFailGuard: CanActivate = { canActivate: jest.fn(() => true) };

    const app: TestingModule = await Test
        controllers: [AppController],
        providers: [

    appController = app.get<AppController>(AppController);

  describe('root', () => {
    it('should return "Hello World!"', () => {
      expect(appController.getHello()).toBe('Hello World!');

How e2e with guard nestjs

By : user3286369
Date : March 29 2020, 07:55 AM
Does that help In a unit test, you test a single unit (service, controller,...) meaning you import one unit and mock all its dependencies. In an e2e test, however, you want to test your whole application so you should import the root module (AppModule) instead of single units or modules. Sometimes you might want to mock particular parts of your application like a database or a 3rd-party API; you can do that with overrideProvider etc.
In your case, you are probably missing the forRoot import of the MongooseModule from your AppModule. Instead of restructuring parts of your application, import the AppModule:
code :
await Test.createTestingModule({
      imports: [AppModule],
const loginResponse = await request(app.getHttpServer())
  .send({ username: 'user', password: '123456' })
// store the jwt token for the next request
const { jwt } = loginResponse.body;

await request(app.getHttpServer())
  // use the jwt to authenticate your request
  .set('Authorization', 'Bearer ' + jwt)
  .expect(res => expect(res.body.users[0])
    .toMatchObject({ username: 'user' }));

Nestjs graphql field guard

By : austinsoft
Date : March 29 2020, 07:55 AM
This might help you So after a few days I found a solution. I wrote a custom Interceptor that looks like this:
code :
import {
} from '@nestjs/common';
// eslint-disable-next-line import/no-extraneous-dependencies
import { Observable } from 'rxjs';
// eslint-disable-next-line import/no-extraneous-dependencies
import { map } from 'rxjs/operators';
import { GqlExecutionContext } from '@nestjs/graphql';
import { ClassTransformOptions } from '@nestjs/common/interfaces/external/class-transform-options.interface';
import { PlainLiteralObject } from '@nestjs/common/serializer/class-serializer.interceptor';
import { CLASS_SERIALIZER_OPTIONS } from '@nestjs/common/serializer/class-serializer.constants';
import { loadPackage } from '@nestjs/common/utils/load-package.util';
import AuthService from './auth.service';

const REFLECTOR = 'Reflector';

let classTransformer: any = {};

class ResourceInterceptor extends ClassSerializerInterceptor {
    @Inject(AuthService) private authService: AuthService,
    @Inject(REFLECTOR) protected readonly reflector: any,
  ) {
    classTransformer = loadPackage('class-transformer', 'ClassSerializerInterceptor', () =>
      // eslint-disable-next-line global-require
    // eslint-disable-next-line global-require

    response: PlainLiteralObject | Array<PlainLiteralObject>,
    options: ClassTransformOptions,
    user: number,
  ): PlainLiteralObject | PlainLiteralObject[] {
    const isArray = Array.isArray(response);
    if (!(typeof response === 'object') && response !== null && !isArray) {
      return response;
    return isArray
      ? (response as PlainLiteralObject[]).map(item => this.transformToClass(item, options))
      : this.transformToGuard(this.transformToClass(response, options), user);

  transformToClass(plainOrClass: any, options: ClassTransformOptions): PlainLiteralObject {
    return plainOrClass && plainOrClass.constructor !== Object
      ? classTransformer.classToClass(plainOrClass, options)
      : plainOrClass;

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const options = this.getContextOptionsCustom(context);
    const ctx = GqlExecutionContext.create(context);
    const { user } = ctx.getContext().req;
    return next.handle().pipe(
      map((res: PlainLiteralObject | Array<PlainLiteralObject>) => {
        return this.serializeCustom(res, options, user);

  private getContextOptionsCustom(context: ExecutionContext): ClassTransformOptions | undefined {
    return (
      this.reflectSerializeMetadataCustom(context.getHandler()) ||

  private reflectSerializeMetadataCustom(
    obj: object | Function,
  ): ClassTransformOptions | undefined {
    return this.reflector.get(CLASS_SERIALIZER_OPTIONS, obj);

  async transformToGuard(response, userId: number) {
    // eslint-disable-next-line no-restricted-syntax
    for (const key of Object.keys(response)) {
      const item = response[key];
      // eslint-disable-next-line no-underscore-dangle
      if (typeof item === 'object' && item !== null && item.__RESOURCE_GUARD__ === true) {
        // eslint-disable-next-line no-await-in-loop
        response[key] = (await this.authService.hasAccess(userId, item.resources))
          ? response[key].value
          : null;
    return response;

export default ResourceInterceptor;
async userGetLogged(@CurrentUser() userId: number) {
  return this.userService.findById(userId);

using path parameters in nestjs guard

By : Store
Date : March 29 2020, 07:55 AM
To fix the issue you can do In your guard you can access the route parameters by getting the request from the context like so:
code :
canActivate(context: ExecutionContext): boolean {
  const request = context.switchToHttp().getRequest();
  const params = request.params;
  const id = params.id; // automatically parsed
Related Posts Related Posts :
  • selenium.JavascriptException: javascript error: Failed to execute 'elementFromPoint' on 'Document': The provided double
  • How can I use Asynchronous Widgets on jupyter lab?
  • Convert Payload with multiple Arrays into a single Array
  • Why zoom level returns decimal?
  • How to do pagination in Druid SQL
  • download data from website using uipath RPA
  • channel Got error &{FORBIDDEN} while joining new peer to a channel
  • How to ensure Screen reader announces capital letters
  • Can You Use a For Loop(s) to Optimize This Code?
  • Is there any way to see query profile for failed queries?
  • Is it possible make Watson Assistant search a data on IBM Cloudant?
  • Is there a way to append incrementally-changing numbers to div class?
  • Calling a Repast model with a list of model parameters
  • Best way to save the contents and configuration of a tk.Text widget?
  • Segmentation fault with openmp in Fortran 90 program
  • Instagram Feed in website - using Instagram Basic Display API
  • Emacs not filling out terminal framebuffer
  • How to instantly detect the key input in AHK?
  • Chisel compiled successfully but can't generate correctly verilog
  • AWS Cognito hosted UI returning id_token in URL
  • Not able to run theharvester on kali linux. Fatal exception: Pycurl: Link time version is older than compile time versio
  • QueryDSL wrong parenthesis with 'OR' and 'AND'
  • Trouble creating a basic clock app for Roku
  • Is there a way to get gerrit to reject commits without a JiRA ticket number?
  • How to print parameter in zimpl format file in lpsolve IDE?
  • How to access hashmap values from payload in dataweave 2.0?
  • Automatic Equation Numbering with MathJax v3.0
  • Unable to serialize IDictionary<string,obj> in ASP.Net Core 3.0 in F#
  • Chisel Synchronization
  • How can i prove that cons after uncons over coinductive list(a.k.a Stream) are identity, in Agda?
  • How to dispatch multiple actions from an effect in ngrx conditionally
  • Is it possible to have multiple valid access token with the same client credentials?
  • How Kafka Streams API get correct schema from Schema Registry?
  • How to cache Styles but still set individual text?
  • .grad() returns None in pytorch
  • Problem how to get the information of a message sent by Telegram
  • Choosing "As data in column" as file name option under Sink Settings for Data Flow is writing data at root of
  • PetitParser: How to match to token set
  • What do those sideways "L" in BBEdit's gutter area mean?
  • Clone Snowflake metadata only
  • Hello! Can someome explain this ```for i, v in pairs(name) do``` for me? Thanks
  • foldr vs foldl as reduce operator in APL
  • DDD, CQRS, Event Sourcing, Aggregates, Related Aggregates, and persistence
  • Uneditable box after ticking it
  • End expected but no clue
  • Extracting kdb list values based on some condition
  • Rounding results in OLS regression
  • How can I add a formula field in my NetSuiite saved search to show me where the invoice date is equal to the due date
  • How can I sorting the grouped rows based on the count of igGrid from infragistics ignite-ui? (jQuery)
  • GOP setting is not honored by Intel H264 hardware MFT
  • Input Parameter filtering with empty value
  • Unhash Drupal 7 Users table Password
  • Mimize default Blazor NavMenu in sidebar
  • Query to get the row counts of all the tables in a database in Snowflake
  • How to stop yup validation on disabled fields?
  • DDD + CQRS + ES: May entities or dtos be part of commands?
  • How to process large number of documents in chunk to avoid expanded tree cache full
  • impala CREATE EXTERNAL TABLE and remove double quotes
  • Web development using Raku
  • Is there any way to develop own Webchat instead of Microsoft Botframework-Webchat
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk