Tom Nurkkala
Tom Nurkkala

Reputation: 652

Access to Apollo server for NestJS GraphQL test

A standard way to test an Apollo GraphQL server is to use the Apollo test client. The createTestClient method requires a server argument. In a NestJS/TypeGraphQL application, what's the appropriate way to access the Apollo server that's created by GraphQLModule from inside a (Jest) test?

Upvotes: 5

Views: 2079

Answers (4)

BRCB
BRCB

Reputation: 1

After searching I ended using this:

import { getApolloServer } from '@nestjs/apollo';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { ApolloServerBase, gql } from 'apollo-server-core';
import { AppModule } from './../src/app.module';

describe('AppController (e2e)', () => {
  let app: INestApplication;
  let apolloServer: ApolloServerBase<any>;

  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleFixture.createNestApplication();
    app.useGlobalPipes(new ValidationPipe());
    await app.init();
    apolloServer = getApolloServer(app);
  });

  afterAll(async () => {
    await app.close();
  });

  it('signUp', async () => {
    const signUpInput = gql`
      mutation Mutation($signUpInput: SignUpInput!) {
        signup(signUpInput: $signUpInput) {
          access
          refresh
        }
      }
    `;
    const signUpResponse = await apolloServer.executeOperation({
      query: signUpInput,
      variables: {
        signUpInput: {
          name: 'John',
          lastName: 'Doe',
          email: '[email protected]',
          password: 'password',
        },
      },
    });
    expect(signUpResponse.data).toBeDefined();
  });
});

Upvotes: 0

Akif Kara
Akif Kara

Reputation: 682

This code worked for me. Thanks to JustMe

import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import { createTestClient, TestQuery } from 'apollo-server-integration-testing';

import { AppModule } from './../src/app.module';
import { GraphQLModule } from '@nestjs/graphql';

describe('AppController (e2e)', () => {
  let app: INestApplication;
  // let mutateTest: TestQuery;
  let correctQueryTest: TestQuery;
  let wrongQueryTest: TestQuery;

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();

    app = moduleFixture.createNestApplication();
    await app.init();
    const module: GraphQLModule =
      moduleFixture.get<GraphQLModule>(GraphQLModule);
    const { query: correctQuery } = createTestClient({
      apolloServer: (module as any).apolloServer,
      extendMockRequest: {
        headers: {
          token:
            'iIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI2MWFiNmY0MjQ3YjEyYWNiNzQyYmQwYmYiLCJyb2xlIjoibWFuYWdlciIsImVtYWlsIjoibGVuYUBtYWlsLmNvbSIsInBhc3N3b3JkIjoiZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2UiLCJ1c2VybmFtZSI6ImxlbmEgZG9lIiwiY3JlYXRlZEF0IjoiMjAyMS0xMi0wNFQxMzozODoxMC4xMzZaIiwidXBkYXRlZEF0IjoiMjAyMS0xMi0wNFQxMzozODoxMC4xMzZaIiwiX192IjowLCJpYXQiOjE2Mzg2NTE4MjMsImV4cCI6MTYzODY1MTg4M30.d6SCh4x6Wwpj16UWf4ca-PbFCo1FQm_bLelp8kscG8U',
        },
      },
    });
    const { query: wrongQuery } = createTestClient({
      apolloServer: (module as any).apolloServer,
    });
    // mutateTest = mutate;
    correctQueryTest = correctQuery;
    wrongQueryTest = wrongQuery;
  });

  it('/ Correct', async () => {
    const result = await correctQueryTest(`
        query FILTER_JOBS{
          filterJobs(status: DONE) {
            title,
            status,
            description,
            lat,
            long,
            employees,
            images,
            assignedBy {
              username,
              email
            }
          }
        }
    `);
    console.log(result);
  });
  it('/ Wrong', async () => {
    const result = await wrongQueryTest(`
        query FILTER_JOBS{
          filterJobs(status: DONE) {
            title,
            status,
            description,
            lat,
            long,
            employees,
            images,
            assignedBy {
              username,
              email
            }
          }
        }
    `);
    console.log(result);
  });
});

Upvotes: 0

Kshateesh
Kshateesh

Reputation: 609

This PR https://github.com/nestjs/graphql/pull/1104 enables you to write tests using apollo-server-testing.

Upvotes: -1

JustMe
JustMe

Reputation: 287

    const moduleFixture = await Test.createTestingModule({
      imports: [ApplicationModule],
    }).compile()
    const app = await moduleFixture.createNestApplication(new ExpressAdapter(express)).init()
    const module: GraphQLModule = moduleFixture.get<GraphQLModule>(GraphQLModule)
    const apolloClient = createTestClient((module as any).apolloServer)

this is what i do

Upvotes: 2

Related Questions