在NestJS中测试Passport

时间:2018-11-12 17:51:15

标签: nestjs

我正在尝试对从nestjs护照模块具有AuthGuard的路由进行e2e测试,我真的不知道该如何处理。当我运行测试时,它说:

  

[ExceptionHandler]未知的身份验证策略“承载者”

我还没有嘲笑它,所以我想是因为这个原因,但是我不知道该怎么做。

这是我到目前为止所拥有的:

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 个答案:

答案 0 :(得分:0)

以下是使用TypeORM和NestJs的passportjs模块的auth API的e2e测试。 auth / authorize API会检查用户是否已登录。 auth / login API会验证用户名/密码组合,并在以下情况下返回Java Web令牌(JWT):查找成功。

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);
  });
});

请注意,因为这是一个端到端测试,所以它不使用模拟(至少我的端到端测试不使用:))。希望这会有所帮助。