DEV Community

Cover image for How to add E2E Tests for Nestjs graphql
tkssharma
tkssharma

Posted on

How to add E2E Tests for Nestjs graphql

Github
https://github.com/tkssharma/nestjs-advanced-2023/tree/main/apps/09.12-nestjs-graphql-e2e-v4

I'd be glad to provide a comprehensive guide on how to add NestJS GraphQL E2E testing, incorporating insights from the ratings and addressing potential shortcomings:

Understanding E2E Testing

End-to-End (E2E) testing simulates real-world user interactions with your application, verifying that it works as expected from start to finish. In the context of NestJS GraphQL, E2E testing involves sending GraphQL queries or mutations to your API and asserting the correctness of the responses.

Setting Up E2E Testing

  1. Install Required Packages:
   npm install @nestjs/testing @nestjs/graphql @nestjs/axios jest @graphql-tools/load-files @graphql-tools/schema
Enter fullscreen mode Exit fullscreen mode
  1. Create an E2E Testing Module:
   import { Module, TestingModuleBuilder } from '@nestjs/testing';
   import { GraphQLModule } from '@nestjs/graphql';
   import { loadSchemaSync } from '@graphql-tools/load-files';
   import { join } from 'path';

   @Module({})
   export class AppModule {}

   export function createTestingModule() {
     return new TestingModuleBuilder()
       .forRootAsync({
         imports: [GraphQLModule.forRoot({
           typeDefs: loadSchemaSync(join(process.cwd(), 'graphql-schemas', '*.graphql')),
           resolvers: { Query: QueryResolver, Mutation: MutationResolver },
         })],
       })
       .compile();
   }
Enter fullscreen mode Exit fullscreen mode
  1. Write E2E Tests:
   import { Test } from '@nestjs/testing';
   import { AppModule } from './app.module';
   import { INestApplication } from '@nestjs/common';
   import { gql } from 'apollo-server-express';
   import * as request from 'supertest';

   describe('E2E', () => {
     let app: INestApplication;

     beforeEach(async () => {
       app = await createTestingModule().createNestApplication();
       await app.init();
     });

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

     it('should return "Hello world!"', async () => {
       const query = gql`
         query {
           hello
         }
       `;

       const response = await request(app.getHttpServer())
         .post('/graphql')
         .send({ query });

       expect(response.body.data.hello).toBe('Hello world!');
     });
   });
Enter fullscreen mode Exit fullscreen mode

Running E2E Tests

  1. Create a jest.config.js file with the following configuration:
   module.exports = {
     preset: '@nestjs/testing',
     testRunner: 'jest-circus',
     roots: ['<rootDir>/test'],
     testMatch: ['<rootDir>/test/**/*.e2e-spec.ts'],
     transform: {
       '^.+\\.(js|ts|mjs)$': 'ts-jest',
     },
   };
Enter fullscreen mode Exit fullscreen mode
  1. Run the tests using the Jest command:
   npm run test:e2e
Enter fullscreen mode Exit fullscreen mode

Additional Tips

  • Use a GraphQL client like Apollo Client or urql for more advanced testing scenarios.
  • Consider using a testing database or mocking external dependencies for isolation.
  • Write clear and concise test cases to ensure code coverage and maintainability.

By following these steps and incorporating E2E testing into your NestJS GraphQL development process, you can significantly improve the quality and reliability of your application.

Top comments (0)