在 NestJS 中测试 Passport

Leo*_*uez 2 nestjs

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

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

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

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

播放器.e2e-规格.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);
  });
});
Run Code Online (Sandbox Code Playgroud)

玩家模块.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 {}
Run Code Online (Sandbox Code Playgroud)

Ric*_*can 6

下面是使用 TypeORM 和 NestJs 的 Passportjs 模块对基于身份验证 API 进行的 e2e 测试。auth /authorize API 检查用户是否已登录。auth /login API 验证用户名/密码组合,如果查找成功,则返回 JSON 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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