Testing Passport in NestJS










0















I'm trying to do a e2e testing to a route that has an AuthGuard from nestjs passport module and I don't really know how to approach it. When I run the tests it says:




[ExceptionHandler] Unknown authentication strategy "bearer"




I haven't mock it yet so I suppose it's because of that but I don't know how to do it.



This is what I have so far:



player.e2e-spec.ts



import Test from '@nestjs/testing';
import INestApplication from '@nestjs/common';
import * as request from 'supertest';
import PlayerModule from '../src/modules/player.module';
import PlayerService from '../src/services/player.service';
import Repository from 'typeorm';

describe('/player', () =>
let app: INestApplication;
const playerService = updatePasswordById: (id, password) => undefined ;

beforeAll(async () =>
const module = await Test.createTestingModule(
imports: [PlayerModule],
)
.overrideProvider(PlayerService)
.useValue(playerService)
.overrideProvider('PlayerRepository')
.useClass(Repository)
.compile();

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

it('PATCH /password', () =>
return request(app.getHttpServer())
.patch('/player/password')
.expect(200);
);
);


player.module.ts



import Module from '@nestjs/common';
import PlayerService from 'services/player.service';
import PlayerController from 'controllers/player.controller';
import TypeOrmModule from '@nestjs/typeorm';
import Player from 'entities/player.entity';
import PassportModule from '@nestjs/passport';

@Module(
imports: [
TypeOrmModule.forFeature([Player]),
PassportModule.register( defaultStrategy: 'bearer' ),
],
providers: [PlayerService],
controllers: [PlayerController],
exports: [PlayerService],
)
export class PlayerModule









share|improve this question




























    0















    I'm trying to do a e2e testing to a route that has an AuthGuard from nestjs passport module and I don't really know how to approach it. When I run the tests it says:




    [ExceptionHandler] Unknown authentication strategy "bearer"




    I haven't mock it yet so I suppose it's because of that but I don't know how to do it.



    This is what I have so far:



    player.e2e-spec.ts



    import Test from '@nestjs/testing';
    import INestApplication from '@nestjs/common';
    import * as request from 'supertest';
    import PlayerModule from '../src/modules/player.module';
    import PlayerService from '../src/services/player.service';
    import Repository from 'typeorm';

    describe('/player', () =>
    let app: INestApplication;
    const playerService = updatePasswordById: (id, password) => undefined ;

    beforeAll(async () =>
    const module = await Test.createTestingModule(
    imports: [PlayerModule],
    )
    .overrideProvider(PlayerService)
    .useValue(playerService)
    .overrideProvider('PlayerRepository')
    .useClass(Repository)
    .compile();

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

    it('PATCH /password', () =>
    return request(app.getHttpServer())
    .patch('/player/password')
    .expect(200);
    );
    );


    player.module.ts



    import Module from '@nestjs/common';
    import PlayerService from 'services/player.service';
    import PlayerController from 'controllers/player.controller';
    import TypeOrmModule from '@nestjs/typeorm';
    import Player from 'entities/player.entity';
    import PassportModule from '@nestjs/passport';

    @Module(
    imports: [
    TypeOrmModule.forFeature([Player]),
    PassportModule.register( defaultStrategy: 'bearer' ),
    ],
    providers: [PlayerService],
    controllers: [PlayerController],
    exports: [PlayerService],
    )
    export class PlayerModule









    share|improve this question


























      0












      0








      0








      I'm trying to do a e2e testing to a route that has an AuthGuard from nestjs passport module and I don't really know how to approach it. When I run the tests it says:




      [ExceptionHandler] Unknown authentication strategy "bearer"




      I haven't mock it yet so I suppose it's because of that but I don't know how to do it.



      This is what I have so far:



      player.e2e-spec.ts



      import Test from '@nestjs/testing';
      import INestApplication from '@nestjs/common';
      import * as request from 'supertest';
      import PlayerModule from '../src/modules/player.module';
      import PlayerService from '../src/services/player.service';
      import Repository from 'typeorm';

      describe('/player', () =>
      let app: INestApplication;
      const playerService = updatePasswordById: (id, password) => undefined ;

      beforeAll(async () =>
      const module = await Test.createTestingModule(
      imports: [PlayerModule],
      )
      .overrideProvider(PlayerService)
      .useValue(playerService)
      .overrideProvider('PlayerRepository')
      .useClass(Repository)
      .compile();

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

      it('PATCH /password', () =>
      return request(app.getHttpServer())
      .patch('/player/password')
      .expect(200);
      );
      );


      player.module.ts



      import Module from '@nestjs/common';
      import PlayerService from 'services/player.service';
      import PlayerController from 'controllers/player.controller';
      import TypeOrmModule from '@nestjs/typeorm';
      import Player from 'entities/player.entity';
      import PassportModule from '@nestjs/passport';

      @Module(
      imports: [
      TypeOrmModule.forFeature([Player]),
      PassportModule.register( defaultStrategy: 'bearer' ),
      ],
      providers: [PlayerService],
      controllers: [PlayerController],
      exports: [PlayerService],
      )
      export class PlayerModule









      share|improve this question
















      I'm trying to do a e2e testing to a route that has an AuthGuard from nestjs passport module and I don't really know how to approach it. When I run the tests it says:




      [ExceptionHandler] Unknown authentication strategy "bearer"




      I haven't mock it yet so I suppose it's because of that but I don't know how to do it.



      This is what I have so far:



      player.e2e-spec.ts



      import Test from '@nestjs/testing';
      import INestApplication from '@nestjs/common';
      import * as request from 'supertest';
      import PlayerModule from '../src/modules/player.module';
      import PlayerService from '../src/services/player.service';
      import Repository from 'typeorm';

      describe('/player', () =>
      let app: INestApplication;
      const playerService = updatePasswordById: (id, password) => undefined ;

      beforeAll(async () =>
      const module = await Test.createTestingModule(
      imports: [PlayerModule],
      )
      .overrideProvider(PlayerService)
      .useValue(playerService)
      .overrideProvider('PlayerRepository')
      .useClass(Repository)
      .compile();

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

      it('PATCH /password', () =>
      return request(app.getHttpServer())
      .patch('/player/password')
      .expect(200);
      );
      );


      player.module.ts



      import Module from '@nestjs/common';
      import PlayerService from 'services/player.service';
      import PlayerController from 'controllers/player.controller';
      import TypeOrmModule from '@nestjs/typeorm';
      import Player from 'entities/player.entity';
      import PassportModule from '@nestjs/passport';

      @Module(
      imports: [
      TypeOrmModule.forFeature([Player]),
      PassportModule.register( defaultStrategy: 'bearer' ),
      ],
      providers: [PlayerService],
      controllers: [PlayerController],
      exports: [PlayerService],
      )
      export class PlayerModule






      nestjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 12 '18 at 18:16







      Leonardo Emilio Dominguez

















      asked Nov 12 '18 at 17:51









      Leonardo Emilio DominguezLeonardo Emilio Dominguez

      788




      788






















          1 Answer
          1






          active

          oldest

          votes


















          0














          Below is a e2e test for an auth API based using TypeORM and the passportjs module for NestJs. the auth/authorize API checks to see if the user is logged in. The auth/login API validates a username/password combination and returns a Java Web Token (JWT) if the lookup is successful.



          import HttpStatus, INestApplication from '@nestjs/common';
          import Test from '@nestjs/testing';
          import TypeOrmModule from '@nestjs/typeorm';
          import * as request from 'supertest';
          import UserAuthInfo from '../src/user/user.auth.info';
          import UserModule from '../src/user/user.module';
          import AuthModule from './../src/auth/auth.module';
          import JWT from './../src/auth/jwt.type';
          import User from '../src/entity/user';

          describe('AuthController (e2e)', () =>
          let app: INestApplication;
          let authToken: JWT;

          beforeAll(async () =>
          const moduleFixture = await Test.createTestingModule(
          imports: [TypeOrmModule.forRoot(), AuthModule],
          ).compile();

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

          it('should detect that we are not logged in', () =>
          return request(app.getHttpServer())
          .get('/auth/authorized')
          .expect(HttpStatus.UNAUTHORIZED);
          );

          it('disallow invalid credentials', async () =>
          const authInfo: UserAuthInfo = username: 'auser', password: 'badpass';
          const response = await request(app.getHttpServer())
          .post('/auth/login')
          .send(authInfo);
          expect(response.status).toBe(HttpStatus.UNAUTHORIZED);
          );

          it('return an authorization token for valid credentials', async () =>
          const authInfo: UserAuthInfo = username: 'auser', password: 'goodpass';
          const response = await request(app.getHttpServer())
          .post('/auth/login')
          .send(authInfo);
          expect(response.status).toBe(HttpStatus.OK);
          expect(response.body.user.username).toBe('auser');
          expect(response.body.user.firstName).toBe('Adam');
          expect(response.body.user.lastName).toBe('User');
          authToken = response.body.token;
          );

          it('should show that we are logged in', () =>
          return request(app.getHttpServer())
          .get('/auth/authorized')
          .set('Authorization', `Bearer $authToken`)
          .expect(HttpStatus.OK);
          );
          );


          Note since this is an end-to-end test, it doesn't use mocking (at least my end-to-end tests don't :)). Hope this is helpful.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267536%2ftesting-passport-in-nestjs%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Below is a e2e test for an auth API based using TypeORM and the passportjs module for NestJs. the auth/authorize API checks to see if the user is logged in. The auth/login API validates a username/password combination and returns a Java Web Token (JWT) if the lookup is successful.



            import HttpStatus, INestApplication from '@nestjs/common';
            import Test from '@nestjs/testing';
            import TypeOrmModule from '@nestjs/typeorm';
            import * as request from 'supertest';
            import UserAuthInfo from '../src/user/user.auth.info';
            import UserModule from '../src/user/user.module';
            import AuthModule from './../src/auth/auth.module';
            import JWT from './../src/auth/jwt.type';
            import User from '../src/entity/user';

            describe('AuthController (e2e)', () =>
            let app: INestApplication;
            let authToken: JWT;

            beforeAll(async () =>
            const moduleFixture = await Test.createTestingModule(
            imports: [TypeOrmModule.forRoot(), AuthModule],
            ).compile();

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

            it('should detect that we are not logged in', () =>
            return request(app.getHttpServer())
            .get('/auth/authorized')
            .expect(HttpStatus.UNAUTHORIZED);
            );

            it('disallow invalid credentials', async () =>
            const authInfo: UserAuthInfo = username: 'auser', password: 'badpass';
            const response = await request(app.getHttpServer())
            .post('/auth/login')
            .send(authInfo);
            expect(response.status).toBe(HttpStatus.UNAUTHORIZED);
            );

            it('return an authorization token for valid credentials', async () =>
            const authInfo: UserAuthInfo = username: 'auser', password: 'goodpass';
            const response = await request(app.getHttpServer())
            .post('/auth/login')
            .send(authInfo);
            expect(response.status).toBe(HttpStatus.OK);
            expect(response.body.user.username).toBe('auser');
            expect(response.body.user.firstName).toBe('Adam');
            expect(response.body.user.lastName).toBe('User');
            authToken = response.body.token;
            );

            it('should show that we are logged in', () =>
            return request(app.getHttpServer())
            .get('/auth/authorized')
            .set('Authorization', `Bearer $authToken`)
            .expect(HttpStatus.OK);
            );
            );


            Note since this is an end-to-end test, it doesn't use mocking (at least my end-to-end tests don't :)). Hope this is helpful.






            share|improve this answer



























              0














              Below is a e2e test for an auth API based using TypeORM and the passportjs module for NestJs. the auth/authorize API checks to see if the user is logged in. The auth/login API validates a username/password combination and returns a Java Web Token (JWT) if the lookup is successful.



              import HttpStatus, INestApplication from '@nestjs/common';
              import Test from '@nestjs/testing';
              import TypeOrmModule from '@nestjs/typeorm';
              import * as request from 'supertest';
              import UserAuthInfo from '../src/user/user.auth.info';
              import UserModule from '../src/user/user.module';
              import AuthModule from './../src/auth/auth.module';
              import JWT from './../src/auth/jwt.type';
              import User from '../src/entity/user';

              describe('AuthController (e2e)', () =>
              let app: INestApplication;
              let authToken: JWT;

              beforeAll(async () =>
              const moduleFixture = await Test.createTestingModule(
              imports: [TypeOrmModule.forRoot(), AuthModule],
              ).compile();

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

              it('should detect that we are not logged in', () =>
              return request(app.getHttpServer())
              .get('/auth/authorized')
              .expect(HttpStatus.UNAUTHORIZED);
              );

              it('disallow invalid credentials', async () =>
              const authInfo: UserAuthInfo = username: 'auser', password: 'badpass';
              const response = await request(app.getHttpServer())
              .post('/auth/login')
              .send(authInfo);
              expect(response.status).toBe(HttpStatus.UNAUTHORIZED);
              );

              it('return an authorization token for valid credentials', async () =>
              const authInfo: UserAuthInfo = username: 'auser', password: 'goodpass';
              const response = await request(app.getHttpServer())
              .post('/auth/login')
              .send(authInfo);
              expect(response.status).toBe(HttpStatus.OK);
              expect(response.body.user.username).toBe('auser');
              expect(response.body.user.firstName).toBe('Adam');
              expect(response.body.user.lastName).toBe('User');
              authToken = response.body.token;
              );

              it('should show that we are logged in', () =>
              return request(app.getHttpServer())
              .get('/auth/authorized')
              .set('Authorization', `Bearer $authToken`)
              .expect(HttpStatus.OK);
              );
              );


              Note since this is an end-to-end test, it doesn't use mocking (at least my end-to-end tests don't :)). Hope this is helpful.






              share|improve this answer

























                0












                0








                0







                Below is a e2e test for an auth API based using TypeORM and the passportjs module for NestJs. the auth/authorize API checks to see if the user is logged in. The auth/login API validates a username/password combination and returns a Java Web Token (JWT) if the lookup is successful.



                import HttpStatus, INestApplication from '@nestjs/common';
                import Test from '@nestjs/testing';
                import TypeOrmModule from '@nestjs/typeorm';
                import * as request from 'supertest';
                import UserAuthInfo from '../src/user/user.auth.info';
                import UserModule from '../src/user/user.module';
                import AuthModule from './../src/auth/auth.module';
                import JWT from './../src/auth/jwt.type';
                import User from '../src/entity/user';

                describe('AuthController (e2e)', () =>
                let app: INestApplication;
                let authToken: JWT;

                beforeAll(async () =>
                const moduleFixture = await Test.createTestingModule(
                imports: [TypeOrmModule.forRoot(), AuthModule],
                ).compile();

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

                it('should detect that we are not logged in', () =>
                return request(app.getHttpServer())
                .get('/auth/authorized')
                .expect(HttpStatus.UNAUTHORIZED);
                );

                it('disallow invalid credentials', async () =>
                const authInfo: UserAuthInfo = username: 'auser', password: 'badpass';
                const response = await request(app.getHttpServer())
                .post('/auth/login')
                .send(authInfo);
                expect(response.status).toBe(HttpStatus.UNAUTHORIZED);
                );

                it('return an authorization token for valid credentials', async () =>
                const authInfo: UserAuthInfo = username: 'auser', password: 'goodpass';
                const response = await request(app.getHttpServer())
                .post('/auth/login')
                .send(authInfo);
                expect(response.status).toBe(HttpStatus.OK);
                expect(response.body.user.username).toBe('auser');
                expect(response.body.user.firstName).toBe('Adam');
                expect(response.body.user.lastName).toBe('User');
                authToken = response.body.token;
                );

                it('should show that we are logged in', () =>
                return request(app.getHttpServer())
                .get('/auth/authorized')
                .set('Authorization', `Bearer $authToken`)
                .expect(HttpStatus.OK);
                );
                );


                Note since this is an end-to-end test, it doesn't use mocking (at least my end-to-end tests don't :)). Hope this is helpful.






                share|improve this answer













                Below is a e2e test for an auth API based using TypeORM and the passportjs module for NestJs. the auth/authorize API checks to see if the user is logged in. The auth/login API validates a username/password combination and returns a Java Web Token (JWT) if the lookup is successful.



                import HttpStatus, INestApplication from '@nestjs/common';
                import Test from '@nestjs/testing';
                import TypeOrmModule from '@nestjs/typeorm';
                import * as request from 'supertest';
                import UserAuthInfo from '../src/user/user.auth.info';
                import UserModule from '../src/user/user.module';
                import AuthModule from './../src/auth/auth.module';
                import JWT from './../src/auth/jwt.type';
                import User from '../src/entity/user';

                describe('AuthController (e2e)', () =>
                let app: INestApplication;
                let authToken: JWT;

                beforeAll(async () =>
                const moduleFixture = await Test.createTestingModule(
                imports: [TypeOrmModule.forRoot(), AuthModule],
                ).compile();

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

                it('should detect that we are not logged in', () =>
                return request(app.getHttpServer())
                .get('/auth/authorized')
                .expect(HttpStatus.UNAUTHORIZED);
                );

                it('disallow invalid credentials', async () =>
                const authInfo: UserAuthInfo = username: 'auser', password: 'badpass';
                const response = await request(app.getHttpServer())
                .post('/auth/login')
                .send(authInfo);
                expect(response.status).toBe(HttpStatus.UNAUTHORIZED);
                );

                it('return an authorization token for valid credentials', async () =>
                const authInfo: UserAuthInfo = username: 'auser', password: 'goodpass';
                const response = await request(app.getHttpServer())
                .post('/auth/login')
                .send(authInfo);
                expect(response.status).toBe(HttpStatus.OK);
                expect(response.body.user.username).toBe('auser');
                expect(response.body.user.firstName).toBe('Adam');
                expect(response.body.user.lastName).toBe('User');
                authToken = response.body.token;
                );

                it('should show that we are logged in', () =>
                return request(app.getHttpServer())
                .get('/auth/authorized')
                .set('Authorization', `Bearer $authToken`)
                .expect(HttpStatus.OK);
                );
                );


                Note since this is an end-to-end test, it doesn't use mocking (at least my end-to-end tests don't :)). Hope this is helpful.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 12 '18 at 18:31









                Rich DuncanRich Duncan

                55638




                55638



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53267536%2ftesting-passport-in-nestjs%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Use pre created SQLite database for Android project in kotlin

                    Darth Vader #20

                    Ondo