【问题标题】:How to create dummy ExecutionContext for CanActivate function for unit testing?如何为 CanActivate 函数创建虚拟 ExecutionContext 以进行单元测试?
【发布时间】:2021-04-23 11:02:11
【问题描述】:

我有带有 canActivate 功能的 authGuard 服务```

canActivate(context: ExecutionContext): boolean |承诺 |可观察的

const ctx = GqlExecutionContext.create(context); const { req } = ctx.getContext();

``` 为了使用一些标头值和所有测试此函数,我需要传递 ExecutionContext。 那么如何创建虚拟 ExecutionContext 来测试这个功能呢? 这是ExecutionContext的接口。
export interface ExecutionContext extends ArgumentsHost {
    /**
     * Returns the *type* of the controller class which the current handler belongs to.
     */
    getClass<T = any>(): Type<T>;
    /**
     * Returns a reference to the handler (method) that will be invoked next in the
     * request pipeline.
     */
    getHandler(): Function;
}


export interface ArgumentsHost {
    /**
     * Returns the array of arguments being passed to the handler.
     */
    getArgs<T extends Array<any> = any[]>(): T;
    /**
     * Returns a particular argument by index.
     * @param index index of argument to retrieve
     */
    getArgByIndex<T = any>(index: number): T;
    /**
     * Switch context to RPC.
     * @returns interface with methods to retrieve RPC arguments
     */
    switchToRpc(): RpcArgumentsHost;
    /**
     * Switch context to HTTP.
     * @returns interface with methods to retrieve HTTP arguments
     */
    switchToHttp(): HttpArgumentsHost;
    /**
     * Switch context to WebSockets.
     * @returns interface with methods to retrieve WebSockets arguments
     */
    switchToWs(): WsArgumentsHost;
    /**
     * Returns the current execution context type (string)
     */
    getType<TContext extends string = ContextType>(): TContext;

}```

【问题讨论】:

    标签: typescript nestjs


    【解决方案1】:

    据我所知,有两种直接的方法可以做到这一点。一种是提供具有所需基本属性的最小对象。可能是这样的:

    const mockContext = {
      switchToHttp: () => ({
        getRequest: () => ({
          headers: {},
          body: {},
          youGetTheIdea: {}
        }),
        getResponse: () => similarResMock,
      })
    }
    

    但是,当您使用GqlExecutionContext 时,您需要将返回值分配给ExecutionContext 拥有的getArgs 方法,而不是switchTo... 方法。看起来像这样:

    const mockContext = {
      getType: () => 'graphql',
      getArgs: () => [{}, {}, gqlContextObject, gqlInfo]
    }
    

    使用这两种方法,除非您想模拟每种方法,否则您需要使用as any

    您的另一个选择是使用模拟对象创建器。如果你使用jest,你可以使用@golevelup/ts-jestcreateMock函数,可以这样使用:

    const mockContext = createMock<ExecutionContext>({
      getType: () => 'graphql',
      getArgs: () => [{}, {}, contextMock, infoMock]
    })
    

    这将返回一个完全有效的ExecutionContext,您可以在不使用as any 或任何其他类型强制方法的情况下传递它。

    I've got an example you can see here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 2012-06-28
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 2020-10-17
      • 2013-11-18
      • 1970-01-01
      相关资源
      最近更新 更多