DEV Community

Abhishek Gupta
Abhishek Gupta

Posted on

Backend Testing β€” Complete Notes

πŸ“Œ 1. What is Backend Testing?

Definition:

Backend testing means checking whether your server-side logic works correctly in all situations.


Simple Understanding:

When a user sends request:

User β†’ API β†’ Backend β†’ Database β†’ Response
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ You must ensure:

  • Correct response is returned
  • Errors are handled properly
  • Data is stored correctly

❗ 2. Why Backend Testing is Important

Without Testing:

  • Bugs go to production ❌
  • Users face crashes ❌
  • Data corruption ❌
  • Security issues ❌

With Testing:

  • Bugs caught early βœ…
  • Safe deployment βœ…
  • Confident coding βœ…
  • Faster development βœ…

Real Example:

Case: User signup API
Enter fullscreen mode Exit fullscreen mode

Without testing:

  • Duplicate emails allowed ❌
  • Password not validated ❌

With testing:

  • Duplicate β†’ rejected βœ…
  • Invalid input β†’ error βœ…

🧠 3. What Should You Test?

You should test:

βœ… Functional Behavior

  • API works correctly

βœ… Validation

  • Wrong input handled

βœ… Security

  • Unauthorized access blocked

βœ… Database

  • Data saved correctly

βœ… Errors

  • Server errors handled

🧩 4. Types of Backend Testing


πŸ”Ή 1. Unit Testing

Definition:

Test single function in isolation


Example:

function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Test:

expect(add(2, 3)).toBe(5);
Enter fullscreen mode Exit fullscreen mode

Features:

  • Fast ⚑
  • No DB
  • No API

πŸ”Ή 2. Integration Testing (MOST IMPORTANT)

Definition:

Test multiple layers together

Route β†’ Controller β†’ Service β†’ DB
Enter fullscreen mode Exit fullscreen mode

Example:

POST /users
Enter fullscreen mode Exit fullscreen mode

Test:

  • Data sent
  • Saved in DB
  • Response returned

πŸ”Ή 3. End-to-End Testing (E2E)

Definition:

Test full user journey


Example:

Register β†’ Login β†’ Access profile
Enter fullscreen mode Exit fullscreen mode

Features:

  • Real-world testing
  • Slower

πŸ—οΈ 5. Backend Testing Tools

πŸ₯‡ Core Tools

  • Jest
  • Supertest
  • MongoDB Memory Server
  • dotenv

🧠 6. Role of Each Tool

πŸ§ͺ Jest

  • Runs tests
  • Provides describe, it, expect
  • Handles assertions
  • Supports mocking

🌐 Supertest

  • Sends HTTP requests
  • Tests APIs like Postman

πŸ—„οΈ MongoMemoryServer

  • Fake DB
  • Fast & isolated

βš™οΈ dotenv

  • Separate test environment

βš™οΈ 7. How Testing Works (Flow)

Jest starts test
 ↓
Supertest sends request
 ↓
Backend processes request
 ↓
DB stores data
 ↓
Response returned
 ↓
Jest verifies result
Enter fullscreen mode Exit fullscreen mode

🧱 8. Basic Setup

Install:

npm install --save-dev jest supertest mongodb-memory-server dotenv
Enter fullscreen mode Exit fullscreen mode

package.json

"scripts": {
  "test": "jest"
}
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 9. First Test Example

import request from 'supertest';
import app from '../app';

describe('GET /', () => {
  it('should return message', async () => {
    const res = await request(app).get('/');

    expect(res.statusCode).toBe(200);
    expect(res.body.message).toBe('API working');
  });
});
Enter fullscreen mode Exit fullscreen mode

πŸ”₯ 10. Real Backend Test Cases

βœ… Success Case

expect(res.statusCode).toBe(200);
Enter fullscreen mode Exit fullscreen mode

❌ Validation Error

expect(res.statusCode).toBe(400);
Enter fullscreen mode Exit fullscreen mode

πŸ”’ Unauthorized

expect(res.statusCode).toBe(401);
Enter fullscreen mode Exit fullscreen mode

πŸ” Duplicate Data

expect(res.body.message).toMatch(/already exists/i);
Enter fullscreen mode Exit fullscreen mode

πŸ’₯ Server Error

expect(res.statusCode).toBe(500);
Enter fullscreen mode Exit fullscreen mode

πŸ” 11. Authentication Testing

let token;

beforeAll(async () => {
  const res = await request(app)
    .post('/login')
    .send({ email, password });

  token = res.body.token;
});

it('should access protected route', async () => {
  const res = await request(app)
    .get('/profile')
    .set('Authorization', `Bearer ${token}`);

  expect(res.statusCode).toBe(200);
});
Enter fullscreen mode Exit fullscreen mode

🧠 12. Database Testing

Use:

  • MongoDB Memory Server

Why:

  • No real DB
  • Fast
  • Clean

πŸ§ͺ 13. Mocking

Why needed?

To avoid calling real services


Example:

jest.mock('../emailService', () => ({
  sendEmail: jest.fn(),
}));
Enter fullscreen mode Exit fullscreen mode

⚑ 14. Best Practices

βœ… Do:

  • Test real API behavior
  • Cover edge cases
  • Keep tests independent

❌ Don’t:

  • Use real DB
  • Start server
  • Ignore errors

🧠 15. Testing Pyramid

Unit β†’ Most
Integration β†’ Medium
E2E β†’ Few
Enter fullscreen mode Exit fullscreen mode

πŸ“Š 16. Code Coverage

npm test -- --coverage
Enter fullscreen mode Exit fullscreen mode

βš™οΈ 17. CI/CD Testing

Use:

  • GitHub Actions

🧠 18. Interview Questions

Q: Why Jest?

πŸ‘‰ Easy + powerful


Q: Why Supertest?

πŸ‘‰ API testing without server


Q: Unit vs Integration?

πŸ‘‰ Function vs full flow


πŸš€ 19. Advanced Topics

  • TDD
  • Load testing
  • Security testing
  • Contract testing

🏁 20. Final Summary

Jest = test runner
Supertest = API tester
DB memory = safe DB
Enter fullscreen mode Exit fullscreen mode

🧠 Final Thought

Testing is not about checking code
It is about preventing failure before users face it

Top comments (0)