NestJS mock JWT authentication in e2e tests

In your overrideGuard(AuthGuard('jwt')).useValue() you can add functionality to your canActivate() function to look like the following:

canActivate (context: ExecutionContext) => {
  const req = context.switchToHttp().getRequest();
  req.user = myCustomUserObject;
  return true;
}

Where myCustomUserObject is the expected value of req.user for the server to handle.


For people using GraphQL, this is what I did:

const module: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    })
      .overrideGuard(JwtAuthGuard)
      .useValue({
        canActivate: (context: ExecutionContext) => {
          const ctx = GqlExecutionContext.create(context)
          ctx.getContext().req.user = { user_id: "abc123" } // Your user object
          return true
        },
      })
      .compile()