【问题标题】:How to test headers request on a nest.js application with Jest如何使用 Jest 在 nest.js 应用程序上测试标头请求
【发布时间】:2021-08-11 03:18:34
【问题描述】:

我正在尝试用 jest 测试一个嵌套应用程序。我有一个调用服务的警卫,在该服务上我必须检查是否存在确定的标头,但我找不到任何有关如何完成此操作的文档。基本上我正在尝试从 nest.js 测试 canActivate 方法

这是我来自 nest.js 的身份验证保护

export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService) { }

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const request = context.switchToHttp().getRequest();
    return this.authService.isValidRequest(request);
  }
}

我想用jest来测试下面的方法,不知道是否需要mock一个Request。如果标头已声明,则该方法将返回 true,否则返回 false。

我不知道如何在单元测试中测试标题。

export class AuthService {
  constructor() { }

  async isValidRequest(req: Request): Promise<boolean> {
 
    const userId = req.headers['user-id'];


    if (userId != 'undefined') {
     
       // I'm going to call another service here
       return true;
      
    }

    return false;
  }

【问题讨论】:

    标签: node.js unit-testing jestjs nestjs


    【解决方案1】:

    老实说,我建议对AuthGuardService 进行单元测试,而不是对AuthGuard 进行测试,只是因为ExecutionContext 有点像野兽。对于一个超级简单的用例,您可以这样做

    describe('AuthGuardService', () => {
      let service: AuthGuardService;
      beforeEach(async () => {
        const modRef = await Test.createTestingModule({
          providers: [
            AuthGuardService,
            { provide: AuthService, useValue: authServiceMock}
          ],
        }).compile();
        service = modRef.get(AuthGuardService);
      });
    
      describe('isValidRequest', () => {
        it('should return true', async () => {
          expect(
            await service.isValidRequest({
              headers: {'user-id': 'some value that is right'}
            } as any
          )).toBe(true);
        });
        it('should return false', async () => {
          expect(
            await service.isValidRequest({
              headers: {'user-id': 'some value that is wrong'}
            } as any
          )).toBe(false);
        });
      });
    });
    

    as any 是为了防止打字稿抱怨。你在这里关心的只是有一个headers proeprty

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-25
      • 1970-01-01
      • 2021-09-10
      • 2013-02-23
      • 2020-02-12
      • 2018-02-24
      • 2016-09-14
      • 2018-09-05
      相关资源
      最近更新 更多