如何对巢中的守卫进行单元测试?

Wil*_*Gao 5 unit-testing typescript jestjs nestjs

我对控制器和服务进行了单元测试,如下所示:

import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

describe('CatsController', () => {
 let catsController: CatsController;
 let catsService: CatsService;

 beforeEach(() => {
   catsService = new CatsService();
   catsController = new CatsController(catsService);
 });

 describe('findAll', () => {
   it('should return an array of cats', async () => {
     const result = ['test'];
     jest.spyOn(catsService, 'findAll').mockImplementation(() => result);

     expect(await catsController.findAll()).toBe(result);
   });
 });
});
Run Code Online (Sandbox Code Playgroud)

但我有一个全局守卫,这个守卫独立于任何控制器或服务,我不知道如何编写 .spec 文件。PLZ

Mic*_*evi 13

我有以下守卫

import { ExecutionContext, Injectable, CanActivate, UnauthorizedException } from '@nestjs/common';
import type { Request } from 'express';

@Injectable()
export class AuthenticatedGuard implements CanActivate {
  canActivate(context: ExecutionContext): true | never {
    const req = context.switchToHttp().getRequest<Request>();
    const isAuthenticated = req.isAuthenticated();
    if (!isAuthenticated) {
      throw new UnauthorizedException();
    }
    return isAuthenticated;
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我的authenticated.guard.spec.ts是:

import { createMock } from '@golevelup/ts-jest';
import { ExecutionContext, UnauthorizedException } from '@nestjs/common';

import { AuthenticatedGuard } from '@/common/guards';

describe('AuthenticatedGuard', () => {
  let authenticatedGuard: AuthenticatedGuard;

  beforeEach(() => {
    authenticatedGuard = new AuthenticatedGuard();
  });

  it('should be defined', () => {
    expect(authenticatedGuard).toBeDefined();
  });

  describe('canActivate', () => {
    it('should return true when user is authenticated', () => {
      const mockContext = createMock<ExecutionContext>();
      mockContext.switchToHttp().getRequest.mockReturnValue({
        // method attached to `req` instance by Passport lib
        isAuthenticated: () => true,
      });

      const canActivate = authenticatedGuard.canActivate(mockContext);

      expect(canActivate).toBe(true);
    });

    it('should thrown an Unauthorized (HTTP 401) error when user is not authenticated', () => {
      const mockContext = createMock<ExecutionContext>();
      mockContext.switchToHttp().getRequest.mockReturnValue({
        // method attached to `req` instance by Passport lib
        isAuthenticated: () => false,
      });

      const callCanActivate = () => authenticatedGuard.canActivate(mockContext);

      expect(callCanActivate).toThrowError(UnauthorizedException);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

灵感来自jmcdo29/testing-nestjs