为什么 Jest 测试通过所有测试用例而跳过用户身份验证?

问题描述 投票:0回答:1

使用 jest 的集成测试会跳过用户身份验证并通过 NestJS 中 grapql 中解析器的所有测试用例。

对于“category.resolver.ts”中的解析器:

import { Args, Mutation, Resolver, Query, Context } from '@nestjs/graphql';
import { CategoryService } from './category.service';
import { UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { UserRole } from '@prisma/client';
import { PrivilegesList } from '../privileges/user-privileges';
import { PermissionsGuardOR } from '../auth/guards/permissions-or.guard';
import { Roles } from '../auth/decorators/roles.decorator';
import { Permissions } from '../auth/decorators/permissions.decorator';
import { Category, PaginatedCategory } from './entities/category.entity';

@Resolver()
export class CategoryResolver {
  constructor(public readonly categoryService: CategoryService) {}

  @Mutation(() => Category)
  @UseGuards(JwtAuthGuard, RolesGuard, PermissionsGuardOR)
  @Roles(UserRole.SUPERADMIN)
  @Permissions([PrivilegesList.CATEGORY_MANAGEMENT.CAPABILITIES.CREATE])
  createCategory(@Args('name') name: string): Promise<Category> {
    return this.categoryService.createCategory(name);
  }
}

我在测试文件“category.resolver.spec.ts”中尝试过:

import { Test, TestingModule } from '@nestjs/testing';
import { CategoryResolver } from './category.resolver';
import { CategoryService } from './category.service';
import { PrismaService } from '../prisma/prisma.service';

describe('CategoryResolver', () => {
  let categoryResolver: CategoryResolver;
  let appSetup;
  let createdCategory;
  let updatedCategory;
  let userRole;

  beforeAll(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [CategoryResolver, CategoryService, PrismaService],
    })
      .compile();

    categoryResolver = module.get<CategoryResolver>(CategoryResolver);
  });

  it('Create category', async () => {
    let createCategoryInput = 'Java';
    createdCategory = await categoryResolver.createCategory(
      createCategoryInput,
    );

    expect(200);
    expect(createdCategory).toHaveProperty(['name']);
  });
}

运行测试后:

/app # 纱线测试类别.resolver.spec.ts
纱线运行v1.22.22
$ 笑话类别.resolver.spec.ts
通过 src/category/category.resolver.spec.ts(7.958 秒)
类别解析器
✓ 创建类别(198 毫秒)

测试套件: 1 个通过,总共 1 个
测试: 1 次通过,总共 1 次
快照:共0张
时间:1.062秒
运行所有匹配 /category.resolver.spec.ts/i.
的测试套件 2.49秒内完成。

graphql nestjs prisma ts-jest
1个回答
0
投票

如果直接调用解析器,则不会考虑

@UseGuards()
装饰器。这是因为它实际上并没有修改该方法,而是添加了 Nest 在运行时读取的元数据,以便在请求实际通过服务器时设置请求链。直接调用解析器会绕过这个,因此在单元测试中不需要任何身份验证

© www.soinside.com 2019 - 2024. All rights reserved.