8

This is a sample of resolver in NestJs, and I'm about to write tests for this file. But there is no documentation for testing resolvers in nestjs docs.

I already have a test for my service, but resolvers also may have little logic inside them, so it's better to have tests for them as well.

How I can test resolver files?

import { ObjectId } from 'mongodb';
import { AuthGuard } from '../utils/Auth.guards';
import { UseGuards } from '@nestjs/common';
import { IUser } from '../users/users.service';
import { User } from '../utils/user.decorator';
import { Query, Resolver, Mutation, Args } from '@nestjs/graphql';
import { AccessService } from './access.service';
import { NeedAccess } from '../utils/needAccess.decorator';
import { HasAccess } from '../utils/access.decorator';

@Resolver('Accesss')
@UseGuards(AuthGuard)
export class AccessResolvers {
  constructor(private readonly accessService: AccessService) {}

  @Query()
  @NeedAccess()
  access(
    @Args('userId') userId: ObjectId,
    @User() user: IUser,
    @HasAccess(['access.view']) hasAccess,
  ) {
    if (userId && hasAccess) { // this might be a situation to concern about in tests
      return this.accessService.getUserAccess(userId);
    } else {
      return this.accessService.getUserAccess(user._id);
    }
  }

}
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Developia
  • 3,928
  • 1
  • 28
  • 43
  • Do you want to write a unit test or an e2e test? – Kim Kern Apr 08 '19 at 21:30
  • Nothing that I have decided right now, I actually look for an easy solution. Beside that knowing how to write unit test or e2e can be beneficial here. :) @KimKern – Developia Apr 09 '19 at 05:04

1 Answers1

4

There is a fundamental difference between unit tests and e2e tests. In unit tests you want to test every corner case of a single, isolated unit, in an e2e test you test the interaction between your units. Both are important, see this answer for a more detailed distinction.

When you write a unit test, you typically mock all dependencies of your unit; in the case of your AccessResolvers the AccessService and then you test every public method. For a detailed example on how to use mocks, see this answer (there is no difference for resolvers).

Kim Kern
  • 54,283
  • 17
  • 197
  • 195