Search code examples
unit-testingnestjs

How to test the return type line of a NestJS resolver with jest


I am new to NestJS and trying to unit test my files to have a good code coverage starter point.

I managed to test everything in my app, except an auth.resolver.ts

Here it is :

import { Resolver, Mutation, Args, Context } from '@nestjs/graphql';
import { ResellerAuthService } from './reseller-auth.service';
import { Response } from 'express';
import { UnauthorizedException } from '@nestjs/common';
import { LoginResellerInput } from './input/login-reseller.input';

@Resolver()
export class AuthResolver {
  constructor(private resellerAuthService: ResellerAuthService) {}

  @Mutation(() => Boolean)
  async loginReseller(
    @Args('loginResellerInput')
    loginResellerInput: LoginResellerInput,
    @Context() context: { res: Response },
  ): Promise<boolean> {
    const authenticated = await this.resellerAuthService.login(
      loginResellerInput,
      context.res,
    );

    if (!authenticated) {
      throw new UnauthorizedException();
    } else return true;
  }
}

And I can't test the return type : @Mutation(() => Boolean)

I tried using :

it('should have a mutation returning Boolean', () => {
  const returnType = Reflect.getMetadata('design:returntype', resolver.constructor.prototype, 'loginReseller');
  expect(returnType).toBe(Boolean);
});

But I know there is only [ 'graphql:resolver_type', 'graphql:resolver_name' ] when logging Reflect.getOwnMetadataKeys(resolver.loginReseller)


Solution

  • Back when I thought that 100% line coverage was a metric to strive for, I found that I could test these methods by extracting the methods to their own variables that could be called directly in the decorators and in the tests. Something like

    export const ReturnsString = () => String;
    

    With this, I could now do @Field(ReturnsString) and in a test something like expect(ReturnsString()).toEqual(String).

    Obviously, this is a pretty ridiculous test that's only there to gain code coverage and doesn't really test anything. This kind of coverage should rather be gained via integration testing of the server, contract testing with the schema, or just general dev work around the server, because if it doesn't work in dev, it won't work in prod.