0
votes

I have authGuard service with canActivate function ```

canActivate(context: ExecutionContext): boolean | Promise | Observable

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

``` For testing this function with some header value and all, I need to pass ExecutionContext. So How to create dummy ExecutionContext for test this function? This is the interface of 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;

}```
1

1 Answers

1
votes

There's two immediate ways I know of you can do this. One is to provide a minimum object that has the base properties you need. Something possibly like this:

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

However, as you're making use of the GqlExecutionContext you'll need to assign the return values to the getArgs method that ExecutionContext has instead of the switchTo... methods. That would look like this:

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

With both of these, unless you want to go and mock out each method, you'll need to use as any.

The other option you have is to use a mock object creator. If you're using jest you can use @golevelup/ts-jest's createMock function, which can be made of use like this:

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

And this will return a fully valid ExecutionContext that you can pass without using as any or any other type coercion methods.

I've got an example you can see here