【问题标题】:How to do unit testing for guard in nest?如何对嵌套中的守卫进行单元测试?
【发布时间】:2021-08-02 09:22:15
【问题描述】:

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

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);
   });
 });
});

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

【问题讨论】:

    标签: unit-testing jestjs nestjs


    【解决方案1】:

    我有下面的守卫

    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;
      }
    }
    

    然后我的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);
        });
      });
    });
    

    灵感来自jmcdo29/testing-nestjs

    【讨论】:

    • 谢谢,你的回答给了我灵感,现在我做到了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    相关资源
    最近更新 更多