Testing Passport in NestJS

╄→尐↘猪︶ㄣ 提交于 2019-12-12 01:03:27

问题


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 {}

回答1:


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 JSON 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.



来源:https://stackoverflow.com/questions/53267536/testing-passport-in-nestjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!