How to unit test the GraphQL components in a Nestjs GraphQL project

Viewed 142

In a Nestjs GraphQL project, we can unit test the revolvers etc by mocking the dependencies,but how to unit test the custom Scalar, Directives, Plugins, exception filter(and exceptions), etc.

1 Answers

You can treat those entities as standard functions or classes in js/ts so, for example, given a scalar like this one:

import {
  Scalar,
  CustomScalar
} from '@nestjs/graphql';
import {
  Kind,
  ValueNode
} from 'graphql';

@Scalar('ReadableDate', () => String)
export class ReadableDate implements CustomScalar < string, Date > {
  description = '`Date` type as a readable string.';

  serialize(value: Date) {
    return value instanceof Date ? `${value}` : value;
  }

  parseValue(value: string | number | null) {
    try {
      const number = Number(value);
      if (isNaN(number)) throw new Error('value is NaN');

      return value !== null ? new Date(number) : null;
    } catch {
      return null;
    }
  }

  parseLiteral(valueNode: ValueNode) {
    if (valueNode.kind === Kind.INT || valueNode.kind === Kind.STRING) {
      try {
        const number = Number(valueNode.value);
        return new Date(number);
      } catch {
        return null;
      }
    }
    return null;
  }
}

You can unit test it like this:

import { ReadableDate } from './readable-date.scalar';

describe('ReadableDate Scalar', () => {
  let scalar, timestamp;
  beforeEach(() => {
      scalar = new ReadableDate();
      timestamp = 1643778000000;
  });
  describe('ReadableDate.parseValue', () => {
    it('should parse a timestamp into a js date', () => {
      expect(scalar.parseValue(timestamp)).toEqual(new Date(timestamp));
    });
    it('should parse a string timestamp into a js date', () => {
      expect(scalar.parseValue(String(timestamp))).toEqual(new Date(timestamp));
    });
    it('should return null when the value given is invalid', () => {
      expect(scalar.parseValue('not a timestamp')).toEqual(null);
    });
  });
});

Related