नमस्ते दोस्तों!
स्वागत है The Easy Master पर!
आपने REST API testing के बारे में तो सीख लिया – Jest aur Supertest ke saath। Ab सोच रहे होंगे: “GraphQL API mein queries aur mutations kaise test karein? Kya same tools kaam karenge?”
Bilkul! Supertest GraphQL API testing ke liye bhi best hai। Kyunki GraphQL bhi HTTP par hi kaam karta hai – bus एक ही endpoint /graphql hota है aur request body mein { query, variables } bhejna hota hai।
Jab maine pehli baar GraphQL API test karna seekha, toh mujhe laga ki alag se kuch complex setup chahiye। Lekin जल्द ही pata chala ki Supertest ke saath query string bhejni है bas। Baaki sab REST jaisa hi है।
Is GraphQL testing Supertest Hindi article mein main aapko sikhata hoon:
✅ GraphQL API testing basics – ek endpoint, queries, mutations
✅ Setup Apollo Server + Supertest – standalone test environment
✅ Query test karein – variables ke saath, nested fields
✅ Mutation test karein – create/update/delete
✅ Error testing – validation errors, GraphQL errors
✅ Mocking resolvers – database aur auth को mock karein
✅ Authentication testing – context mein user inject karein
✅ Best practices – test isolation, coverage, CI/CD
✅ Real example – User + Post GraphQL API tests
Chaliye GraphQL API testing ka magic seekhte hain! 🚀
Table of Contents
1. GraphQL API Testing – क्यों अलग नहीं है?
GraphQL API testing essentially REST API testing jaisa hi hai, bas difference ye hai ki:
- Ek hi endpoint –
/graphqlपर सारे requests jaate hain - Request body mein –
query(string) aurvariables(object) bhejna hota hai - Response structure –
dataaurerrorsfields hote hain
| Aspect | REST API | GraphQL API |
|---|---|---|
| Endpoint | Multiple (/users, /posts) | Single (/graphql) |
| Request body | JSON object according to endpoint | { query, variables } |
| Error handling | HTTP status codes (400, 401, 404, 500) | errors array + HTTP 200 mostly |
| Testing tool | Supertest | Supertest (same!) |
GraphQL testing ke liye supertest perfect है – aapko bus query string ko POST body mein bhejna है।
Kapde ki boli: GraphQL testing = REST testing + ek extra
queryfield। Baaki sab same है।
2. Setup – Apollo Server + Supertest Integration
Chaliye ek simple GraphQL API banate hain aur uske tests likhte hain।
2.1 Project Setup
mkdir graphql-testing-demo
cd graphql-testing-demo
npm init -y2.2 Install Dependencies
# Apollo Server
npm install @apollo/server graphql
# Testing
npm install --save-dev jest supertest typescript ts-jest @types/jest @types/supertest @types/node2.3 Configure Jest
jest.config.js:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/*.test.ts'],
};package.json scripts:
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}2.4 Create GraphQL Schema & Resolvers
src/schema.ts:
export const typeDefs = `#graphql
type User {
id: ID!
name: String!
email: String!
}
type Query {
users: [User!]!
user(id: ID!): User
}
type Mutation {
createUser(name: String!, email: String!): User!
updateUser(id: ID!, name: String, email: String): User!
deleteUser(id: ID!): Boolean!
}
`;src/resolvers.ts:
import { GraphQLError } from 'graphql';
interface User {
id: string;
name: string;
email: string;
}
// In-memory database
let users: User[] = [
{ id: '1', name: 'Vivek', email: 'vivek@example.com' },
{ id: '2', name: 'Deepti', email: 'deepti@example.com' },
];
let nextId = 3;
export const resolvers = {
Query: {
users: () => users,
user: (_: any, { id }: { id: string }) => {
const user = users.find(u => u.id === id);
if (!user) {
throw new GraphQLError('User not found', {
extensions: { code: 'USER_NOT_FOUND' }
});
}
return user;
},
},
Mutation: {
createUser: (_: any, { name, email }: { name: string; email: string }) => {
const newUser = { id: String(nextId++), name, email };
users.push(newUser);
return newUser;
},
updateUser: (_: any, { id, name, email }: { id: string; name?: string; email?: string }) => {
const index = users.findIndex(u => u.id === id);
if (index === -1) {
throw new GraphQLError('User not found', {
extensions: { code: 'USER_NOT_FOUND' }
});
}
users[index] = { ...users[index], ...(name && { name }), ...(email && { email }) };
return users[index];
},
deleteUser: (_: any, { id }: { id: string }) => {
const index = users.findIndex(u => u.id === id);
if (index === -1) return false;
users.splice(index, 1);
return true;
},
},
};2.5 Create Apollo Server (No Listen)
Important: Server ko listen call karke real port bind nahi karna – Supertest direct ApolloServer ke executeOperation method se kaam कर सकता है, lekin hum Supertest ke saath real HTTP request simulate karna चाहते हैं। To hum expressMiddleware use karenge।
src/server.ts:
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
async function createTestServer() {
const app = express();
app.use(express.json());
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
app.use('/graphql', expressMiddleware(server));
return app;
}
export default createTestServer;src/index.ts (real server – optional):
import createTestServer from './server';
const app = await createTestServer();
const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log(`Server ready at http://localhost:${PORT}/graphql`));3. Pehla Query Test – Status Code aur Response Structure
Ab test likhte hain। Create src/__tests__/graphql.test.ts:
import request from 'supertest';
import createTestServer from '../server';
describe('GraphQL API Tests', () => {
let app: any;
beforeAll(async () => {
app = await createTestServer();
});
describe('Query users', () => {
it('should return all users', async () => {
const query = `
query {
users {
id
name
email
}
}
`;
const response = await request(app)
.post('/graphql')
.send({ query })
.expect(200);
expect(response.body).toHaveProperty('data');
expect(response.body.data.users).toHaveLength(2);
expect(response.body.data.users[0]).toHaveProperty('name', 'Vivek');
});
});
});Code Explanation
| Code | Meaning |
|---|---|
beforeAll(async () => { app = await createTestServer(); }) | Tests se pehle ek baar server create karo |
request(app).post('/graphql') | Supertest se POST request /graphql endpoint par |
.send({ query }) | Body mein GraphQL query bhejo |
.expect(200) | Status code 200 expected (GraphQL always 200 unless server error) |
expect(response.body).toHaveProperty('data') | Response mein data field hona चाहिए |
expect(response.body.data.users[0].name).toBe('Vivek') | Data ka structure check karo |
4. Variables Ke Saath Query Test Karein
Dynamic queries ke liye variables use karte hain। Supertest mein variables bhejne ka tarika:
it('should fetch single user by id', async () => {
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
}
}
`;
const variables = { id: '1' };
const response = await request(app)
.post('/graphql')
.send({ query, variables })
.expect(200);
expect(response.body.data.user.name).toBe('Vivek');
expect(response.body.data.user.email).toBe('vevek@example.com');
});Check non-existent user error:
it('should return error for non-existent user', async () => {
const query = `
query GetUser($id: ID!) {
user(id: $id) {
id
name
}
}
`;
const variables = { id: '999' };
const response = await request(app)
.post('/graphql')
.send({ query, variables })
.expect(200); // GraphQL error still returns 200
expect(response.body).toHaveProperty('errors');
expect(response.body.errors[0].extensions.code).toBe('USER_NOT_FOUND');
});5. Mutation Test – Create aur Update Operations
Mutations bhi queries ki tarah test hoti hain – bus operation type mutation hota है।
5.1 Create User Mutation Test
describe('Mutation createUser', () => {
it('should create a new user', async () => {
const mutation = `
mutation CreateUser($name: String!, $email: String!) {
createUser(name: $name, email: $email) {
id
name
email
}
}
`;
const variables = { name: 'Test User', email: 'test@example.com' };
const response = await request(app)
.post('/graphql')
.send({ query: mutation, variables })
.expect(200);
expect(response.body.data.createUser).toHaveProperty('id');
expect(response.body.data.createUser.name).toBe('Test User');
expect(response.body.data.createUser.email).toBe('test@example.com');
});
});5.2 Update User Mutation Test
it('should update user name', async () => {
const mutation = `
mutation UpdateUser($id: ID!, $name: String) {
updateUser(id: $id, name: $name) {
id
name
email
}
}
`;
const variables = { id: '1', name: 'Vivek Updated' };
const response = await request(app)
.post('/graphql')
.send({ query: mutation, variables })
.expect(200);
expect(response.body.data.updateUser.name).toBe('Vivek Updated');
});5.3 Delete User Mutation Test
it('should delete a user', async () => {
const mutation = `
mutation DeleteUser($id: ID!) {
deleteUser(id: $id)
}
`;
const variables = { id: '2' };
const response = await request(app)
.post('/graphql')
.send({ query: mutation, variables })
.expect(200);
expect(response.body.data.deleteUser).toBe(true);
});6. GraphQL Error Testing – Validation aur Authentication
GraphQL mein errors HTTP status code se nahi, balki errors array se aati hain। Status code normally 200 रहता है (unless server crash)।
6.1 Validation Error (Missing Required Field)
it('should return error when email missing in createUser', async () => {
const mutation = `
mutation {
createUser(name: "No Email") {
id
name
}
}
`;
const response = await request(app)
.post('/graphql')
.send({ query: mutation })
.expect(200);
expect(response.body).toHaveProperty('errors');
expect(response.body.errors[0].extensions.code).toBeDefined();
});6.2 Custom GraphQLError Assertions
it('should return USER_NOT_FOUND error for invalid update', async () => {
const mutation = `
mutation {
updateUser(id: "999", name: "Ghost") {
id
name
}
}
`;
const response = await request(app)
.post('/graphql')
.send({ query: mutation });
expect(response.body.errors[0].extensions.code).toBe('USER_NOT_FOUND');
});7. Mocking Resolvers – Database aur Auth Mock Kaise Karein
Real tests mein external dependencies (database, external APIs) ko mock karna better practice hai। Jest ke mocking features use karte hain।
7.1 Mock Entire Resolvers Module
src/__tests__/mocked.test.ts:
import request from 'supertest';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import { typeDefs } from '../schema';
// Mock resolvers
const mockResolvers = {
Query: {
users: jest.fn().mockReturnValue([
{ id: 'm1', name: 'Mock User', email: 'mock@test.com' }
]),
},
Mutation: {
createUser: jest.fn().mockImplementation((_, { name, email }) => ({
id: 'mock-id',
name,
email,
})),
},
};
describe('Mocked Resolvers Test', () => {
let app: any;
beforeAll(async () => {
const server = new ApolloServer({ typeDefs, resolvers: mockResolvers });
await server.start();
const expressApp = express();
expressApp.use(express.json());
expressApp.use('/graphql', expressMiddleware(server));
app = expressApp;
});
it('should use mocked users', async () => {
const response = await request(app)
.post('/graphql')
.send({ query: '{ users { id name } }' });
expect(response.body.data.users[0].name).toBe('Mock User');
expect(mockResolvers.Query.users).toHaveBeenCalled();
});
});7.2 Mock Database Module
Agar aapne database operations ko alag module mein rakha hai, to usse mock kar sakte ho:
jest.mock('../db', () => ({
getUsers: jest.fn().mockResolvedValue([{ id: '1', name: 'Db User' }]),
createUser: jest.fn().mockImplementation((user) => Promise.resolve({ id: 'new', ...user })),
}));8. Test Isolation – beforeEach/afterEach se State Reset
In-memory database use kar rahe ho to tests ke beech state reset karna important hai।
8.1 Reset Users Array Before Each Test
src/__tests__/isolated.test.ts:
import request from 'supertest';
import createTestServer from '../server';
import { resolvers } from '../resolvers';
// Access the users array from resolvers module
// For this to work, you'd need to export users array or use a test helper
describe('Isolated tests', () => {
let app: any;
beforeAll(async () => {
app = await createTestServer();
});
beforeEach(() => {
// Reset users array to initial state
// If using a module that exposes reset function, call it
// Here we assume resolvers have a reset function
// Example: resetUsers();
});
it('should start with 2 users', async () => {
const response = await request(app)
.post('/graphql')
.send({ query: '{ users { id } }' });
expect(response.body.data.users).toHaveLength(2);
});
});💡 Pro Tip: Production code mein test helpers export kar sakte ho –
resetDatabase(),seedTestData(), etc। Test environment mein inhein expose karo, production build में exclude।
9. Authentication Testing – Context Injection
Apollo Server mein context function authentication data inject kar sakta hai। Test mein aap mock context bana sakte ho।
9.1 Server with Auth Context
src/auth-server.ts:
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
interface MyContext {
user?: { id: string; role: string };
}
export async function createAuthTestServer(contextValue?: MyContext) {
const app = express();
app.use(express.json());
const server = new ApolloServer<MyContext>({ typeDefs, resolvers });
await server.start();
app.use('/graphql', expressMiddleware(server, {
context: async () => contextValue || { user: undefined },
}));
return app;
}9.2 Test Protected Resolver (If Any)
it('should allow access with valid user context', async () => {
const app = await createAuthTestServer({ user: { id: '123', role: 'ADMIN' } });
const response = await request(app)
.post('/graphql')
.send({ query: '{ users { name } }' });
expect(response.status).toBe(200);
expect(response.body.data).toBeDefined();
});10. Best Practices – Production-Level Tips
✅ Use beforeAll to create server once – Har test ke liye server recreate mat karo (slow होगा)। Ek baar banake reuse करो।
✅ Test both success and error cases – Har mutation ke liye success path, validation errors, not found errors – sab test karo।
✅ Keep tests isolated – Ek test doosre test ke data par depend नहीं होना चाहिए। Use beforeEach to reset state。
✅ Use variables for queries – Hardcoded query strings se better readability aur type safety।
✅ Test error extensions/codes – Sirf error message nahi, specific error code bhi check karo (clients error code handle karte hain)。
✅ Mock external dependencies – Database, external APIs, file system – sabko mock करो taaki tests fast rahein।
✅ Run tests in CI/CD – GitHub Actions, GitLab CI, ya Jenkins mein tests automatically run karo।
✅ Maintain coverage – 70-80% coverage is good enough, focus on critical paths。
✅ Use expect.assertions for async error tests – Ensure that certain number of assertions are called।
💡 Personal Experience: Maine ek baar ek mutation test likha without verifying the error code – sirf message check kiya। Baad mein backend ne error code change kar diya, lekin message same था। Test pass ho gaya, लेकिन client integration टूट गया। अब main hamesha error code bhi check karta हूँ।
11. Resources – Cheat Sheet & Practice Prompts
GraphQL Supertest Cheat Sheet
// Query without variables
await request(app)
.post('/graphql')
.send({ query: '{ users { id name } }' })
.expect(200);
// Query with variables
await request(app)
.post('/graphql')
.send({
query: 'query GetUser($id: ID!) { user(id: $id) { name } }',
variables: { id: '1' }
})
.expect(200);
// Mutation
await request(app)
.post('/graphql')
.send({
query: 'mutation { createUser(name: "Test", email: "t@t.com") { id } }'
});
// Error checking
expect(response.body).toHaveProperty('errors');
expect(response.body.errors[0].extensions.code).toBe('USER_NOT_FOUND');Practice Prompts
Beginner:
- Simple Book GraphQL API banayein (type:
Book { id, title, author })। Queries:books,book(id). Mutation:addBook. Tests likhein for GET books, get by id, and add book।
Intermediate:
- Authentication add karein – JWT token validate karo in context। Tests likhein for authenticated vs unauthenticated requests। Mock JWT verify function।
Advanced:
- DataLoader implement karein to solve N+1 problem। Mock DataLoader in tests। Write tests for nested query
users { posts { title } }and verify DataLoader batch calls।
12. FAQ
Q1: GraphQL API testing mein status code 200 kyun aata hai error par bhi?
GraphQL design philosophy ke अनुसार, HTTP 200 का मतलब है कि server ने request को successfully parse kar liya और response bhej diya। Actual business errors errors array mein aati hain। Isliye GraphQL API testing mein aapko response.body.errors check karna hota hai, not status code।
Q2: Supertest ko Apollo Server ke saath kaise use karein?
expressMiddleware use karke Express app banayein, usse Supertest mein pass karein। Direct Apollo Server executeOperation bhi use kar sakte ho, lekin Supertest HTTP request ko realistically simulate karta है।
Q3: Variables wali queries test kaise karein?
Send method mein { query, variables } object pass karo। Variables object mein named arguments ki values bhejo।
Q4: Mock resolvers test mein kaise use karein?
Test ke andar naye ApolloServer instance banayein with your mock resolvers object (instead of real resolvers)। Isse aap database calls bypass kar sakte ho।
Q5: Database state reset kaise karein between tests?
beforeEach hook mein database को initial state में reset करो। For in-memory, reinitialize array। For real database, use transactions or mongodb-memory-server।
Q6: CI/CD pipeline mein GraphQL tests kaise run karein?
GitHub Actions mein same as REST tests – npm install && npm test। Ensure Apollo Server doesn’t actually listen on a port; use the Express app with supertest। No need to start separate server process।
13. Conclusion – Ab Aapki Baari!
Bahut badhiya! Aapne aaj seekh liya:
✅ GraphQL testing Supertest Hindi – complete practical guide
✅ Setup Apollo Server + Supertest – expressMiddleware integration
✅ Query tests – variables ke saath, nested fields
✅ Mutation tests – create, update, delete
✅ Error testing – GraphQL errors and extensions
✅ Mocking resolvers and dependencies
✅ Authentication testing – context injection
✅ Best practices – test isolation, CI/CD, coverage
GraphQL API testing utna hi simple है jitna REST API testing – bas query string को POST body mein bhejna है। Supertest ke saath aap production-grade tests likh sakte ho jo confidence देते हैं।
Aapki challenge: Complete User + Post GraphQL API banayein। Tests likhein for: fetching users with their posts, creating a post with author validation, updating a post, deleting a post with authentication। Mock the authentication context। Apna code comment mein share karo!
Next topic kya chahiye?
- GraphQL Subscription Testing with WebSocket?
- End-to-end Testing with Cypress?
- Performance Testing GraphQL APIs with k6?
Comment mein batao!
The Easy Master ke saath GraphQL testing seekhte raho। Happy testing! 🚀
Resources
- Apollo Server Testing Guide (Official)
- Supertest Documentation
- Testing GraphQL APIs with Jest (LogRocket)
- GraphQL Error Handling Best Practices
Additional Resources
- MongoDB Setup – CRUD Operations समझे (Beginner Guide) 2026
- MongoDB Compass से GUI Database Manage करने का आसान तरीका | Beginner Tutorial 2026
- Node.js MongoDB Connection – Mongoose Setup समझे 2026
- MongoDB Data Modeling – Embedded Documents vs References 2026
- MongoDB Indexing – Query Speed बढ़ने करने का आसान तरीका
- MongoDB Aggregation Pipeline – Stages समझे | Practical Examples
- Express MongoDB CRUD – Complete REST API Example
- Mongoose ODM – Schema, Model, and Validation समझे 2026
- MongoDB Atlas – Cloud Database Free में Deploy करें 2026
- JWT Authentication MongoDB – User Login System कैसे बनाएं 2026
- Next.js App Router – Pages Router से क्या बदला? Complete Guide 2026
- Next.js Server Components – ‘use client’ कब और कहां Use करें
- Next.js Routing – Layouts, Dynamic Routes and Nested Routes 2026
- Next.js 16 New Features – Turbopack, Cache Components and proxy.ts
- Next.js Partial Prerendering – Static and Dynamic Content साथ में
- Next.js Authentication – JWT Session Management (App Router) 2026
- Next.js SEO – Metadata API and Image Optimization समझे 2026
- Next.js TypeScript – Full-Stack Type-Safe App कैसे बनाएं
- FastAPI Kya Hai? FastAPI Python Setup Aur Pehla API Hindi 2026
- FastAPI Path Parameters Hindi – शून्य से हीरो तक गाइड 2026
- Pydantic v2 Tutorial Hindi – Data Validation Master 2026
- FastAPI dependency injection Hindi – Code Reuse Ka Magic
- FastAPI Async Await Hindi – Non-Blocking Code 2026
- FastAPI PostgreSQL SQLModel Hindi – Async Guide 2026
- FastAPI JWT Authentication Hindi – Secure API Login
- FastAPI OpenAI Integration Hindi – AI Chatbot API 2026
- FastAPI Multi-Agent AI Hindi – LangGraph Zero to Hero
- FastAPI Deployment Hindi – Railway Zero to Hero 2026
- Docker Introduction in Hindi? Containers vs Virtual Machines
- Docker Images and Containers Hindi – Pehla Container
- Docker Compose Tutorial Hindi – Node.js + MongoDB
- Docker Volumes Networking Hindi – Data Persist कैसे करें
- Kubernetes Architecture Hindi – Pods, Nodes, Cluster
- Minikube Tutorial Hindi – Local Cluster कैसे बनाए
- Kubernetes Deployments Services Hindi – App Expose Karein
- K8s Ingress Tutorial Hindi – Domain se App Access
- Helm Kya Hai? – Kubernetes Charts Se App Deploy
- GraphQL Introduction in Hindi – REST vs GraphQL Comparison
- GraphQL Schema Tutorial Hindi – Types Queries Resolvers
- GraphQL Queries Mutations Hindi – Frontend Integration
- GraphQL Advanced Features Hindi – Fragments Aliases Variables
- Apollo Server GraphQL Node.js TypeScript Hindi – API Kaise Banaye
- Apollo Client React Hindi – GraphQL Queries Use Kaise Karein
Views: 285