在NestJS中测试Passport [英] Testing Passport in NestJS

查看:562
本文介绍了在NestJS中测试Passport的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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]未知的身份验证策略承载者"

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

推荐答案

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

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.

这篇关于在NestJS中测试Passport的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆