gpt4 book ai didi

nestjs - 在 NestJS 中测试护照

转载 作者:行者123 更新时间:2023-12-01 22:02:28 25 4
gpt4 key购买 nike

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

[ExceptionHandler] Unknown authentication strategy "bearer"

我还没有模拟它,所以我想是因为那个,但我不知道该怎么做。

这是我目前所拥有的:

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 的端到端测试。 auth/authorize API 检查用户是否已登录。auth/login API 验证用户名/密码组合并返回一个 JSON Web token (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);
});
});

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

关于nestjs - 在 NestJS 中测试护照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53267536/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com