本文介绍了NestJS:如何在 canActivate 中模拟 ExecutionContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Guard 中间件中模拟 ExecutionContext 时遇到问题.

I am having trouble in mocking ExecutionContext in Guard middleware.

这是我的 RoleGuard 扩展 JwtGuard

Here's my RoleGuard extends JwtGuard

@Injectable()
export class RoleGuard extends JwtAuthGuard {
 ...
 async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const params = request.params;

    ...
 }
}

这就是我正在尝试的单元测试.

This is what I am trying on my unit test.

let context: ExecutionContext = jest.genMockFromModule('@nestjs/common');

context.switchToHttp = jest.fn().mockResolvedValue({
  getRequest: () => ({
   originalUrl: '/',
   method: 'GET',
   params: undefined,
   query: undefined,
   body: undefined,
  }),
  getResponse: () => ({
    statusCode: 200,
  }),
});

jest.spyOn(context.switchToHttp(), 'getRequest').mockImplementation(() => {
 return Promise.resolve(null);
});

我遇到了这种错误.

Cannot spy the getRequest property because it is not a function; undefined given instead

我希望您提出任何其他模拟上下文的方法.谢谢.

I would like you to suggest any other way to mock context. Thank you.

推荐答案

请检查这个库 https://www.npmjs.com/package/@golevelup/ts-jest

然后你可以模拟 ExecutionContext 如下.

Then you could mock ExecutionContext as following.

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

describe('Mocked Execution Context', () => {
  it('should have a fully mocked Execution Context', () => {
    const mockExecutionContext = createMock<ExecutionContext>();
    expect(mockExecutionContext.switchToHttp()).toBeDefined();

    ...

  });
});

希望能帮到你

这篇关于NestJS:如何在 canActivate 中模拟 ExecutionContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 17:46