Introduction
In the previous article, we learned:
Docker
Containers
Docker Compose
Multi-container architecture
Kubernetes basics
Cloud-native deployment
Now it is time to learn one of the most important professional development skills:
Testing and Debugging
Large applications can contain:
Bugs
Logic errors
API failures
UI issues
Security vulnerabilities
Testing helps ensure applications work correctly before users access them.
In this article, we will learn:
What testing is
Types of testing
Unit testing
Integration testing
API testing
Jest
React Testing Library
Backend testing
Debugging techniques
What is Testing?
Testing means:
Checking whether application features work correctly
Why Testing is Important
Testing helps:
Reduce bugs
Improve reliability
Prevent crashes
Increase code quality
Build stable applications
Types of Testing
| Testing Type | Purpose |
|---|---|
| Unit Testing | Test small functions |
| Integration Testing | Test connected modules |
| API Testing | Test backend APIs |
| End-to-End Testing | Test complete application |
What is Unit Testing?
Unit testing checks:
Small individual parts of code
Example:
Functions
Components
Utility methods
Example Function
function add(a, b) {
return a + b;
}
Unit Test Example
test('adds numbers correctly', () => {
expect(add(2, 3)).toBe(5);
});
Understanding test()
test()
defines test case.
Understanding expect()
expect()
checks expected result.
What is Jest?
Jest is a popular testing framework for:
React
Node.js
JavaScript applications
Why Jest is Popular
Jest provides:
Simple syntax
Fast testing
Mocking support
Snapshot testing
Installing Jest in Backend
npm install --save-dev jest
Updating package.json
"scripts": {
"test": "jest"
}
Running Tests
npm test
Creating Test Files
Example:
math.test.js
Example Test File
const add = require('./math');
test('adds numbers', () => {
expect(add(5, 5)).toBe(10);
});
Understanding toBe()
toBe()
checks exact values.
Common Jest Matchers
| Matcher | Purpose |
|---|---|
| toBe() | Exact value |
| toEqual() | Object comparison |
| toContain() | Check arrays |
| toBeTruthy() | Boolean checks |
Example toContain()
expect(['apple', 'mango'])
.toContain('apple');
Testing Async Functions
Backend APIs often use:
async/await
Async Test Example
test('fetch users', async () => {
const data = await getUsers();
expect(data.length).toBe(3);
});
API Testing
API testing checks:
Routes
Responses
Status codes
Authentication
Installing Supertest
npm install --save-dev supertest
What is Supertest?
SuperTest helps test Express APIs.
Example API Test
const request = require('supertest');
const app = require('./app');
test('GET /students', async () => {
const response = await request(app)
.get('/students');
expect(response.statusCode).toBe(200);
});
Testing POST APIs
test('create student', async () => {
const response = await request(app)
.post('/students')
.send({
name: 'Rahul'
});
expect(response.statusCode)
.toBe(201);
});
Mocking in Jest
Mocking means:
Creating fake versions of functions or APIs
Why Mocking is Useful
Mocking prevents:
Real API calls
Database modifications
Slow tests
Example Mock Function
jest.fn()
Mock API Example
jest.mock('axios');
Frontend Testing in React
React applications commonly use:
React Testing Library
Installing React Testing Library
npm install @testing-library/react
What React Testing Library Does
It tests:
Components
Buttons
Inputs
User interactions
Example React Component
function Button() {
return <button>Click Me</button>;
}
Testing React Component
import {
render,
screen
} from '@testing-library/react';
import Button from './Button';
test('button renders', () => {
render(<Button />);
expect(
screen.getByText('Click Me')
).toBeInTheDocument();
});
Understanding render()
render()
renders component virtually for testing.
Understanding screen()
screen()
searches rendered elements.
Testing User Interactions
React Testing Library supports:
Click events
Form inputs
Typing simulation
Example Click Test
import userEvent from
'@testing-library/user-event';
Button Click Example
test('button click', async () => {
render(<Button />);
const button = screen.getByText(
'Click Me'
);
await userEvent.click(button);
});
What is Snapshot Testing?
Snapshot testing compares:
UI changes over time
Snapshot Example
expect(container)
.toMatchSnapshot();
End-to-End Testing
End-to-end testing checks:
Complete application workflow
Example:
Login
Dashboard access
Logout
Popular E2E Testing Tools
| Tool | Purpose |
|---|---|
| Cypress | Frontend testing |
| Playwright | Browser automation |
What is Cypress?
Cypress tests real browser interactions.
Installing Cypress
npm install cypress --save-dev
Running Cypress
npx cypress open
Example Cypress Test
describe('Login Test', () => {
it('logs user in', () => {
cy.visit('/login');
cy.get('input[type=email]')
.type('test@gmail.com');
cy.get('button')
.click();
});
});
What is Debugging?
Debugging means:
Finding and fixing errors in code
Common Types of Bugs
| Bug Type | Example |
|---|---|
| Syntax Error | Missing bracket |
| Logical Error | Wrong calculation |
| Runtime Error | Undefined variable |
Using console.log()
Most basic debugging method:
console.log(data);
Browser Developer Tools
Modern browsers provide:
Developer Tools
Shortcut:
F12
Useful DevTools Tabs
| Tab | Purpose |
|---|---|
| Console | Errors and logs |
| Network | API requests |
| Elements | HTML inspection |
Debugging Backend APIs
Use:
Morgan
Postman
Thunder Client
to inspect backend behavior.
Handling Errors Properly
Always use:
try...catch
Example
try {
const data = await fetchUsers();
} catch (err) {
console.error(err.message);
}
Logging Errors
Useful logging libraries:
Winston
Morgan
Pino
What is Code Coverage?
Code coverage measures:
How much code is tested
Running Coverage Report
npm test -- --coverage
Benefits of Testing
Testing improves:
Stability
Maintainability
Security
Developer confidence
Common Beginner Mistakes
Not Testing Edge Cases
Example:
Empty input
Invalid email
Large files
Testing Too Little
Important features must always be tested.
Ignoring Error Handling
Always test:
Invalid requests
Unauthorized access
Database failures
Best Practices
Write Small Tests
Small tests are:
Easier to debug
Faster to run
Use Separate Test Files
Example:
auth.test.js
student.test.js
Automate Testing
Use CI/CD pipelines to run tests automatically.
Test Critical Features First
Priority:
Authentication
Payments
Database operations
Real-World Testing Workflow
Professional workflow:
Write Code
↓
Write Tests
↓
Run Tests
↓
Fix Bugs
↓
Deploy Application
Real-World Companies Using Automated Testing
Testing is heavily used by:
Google
Netflix
Amazon
Facebook
Microsoft
Conclusion
You have now learned testing and debugging in the PERN stack.
You learned:
Unit testing
API testing
Jest
React Testing Library
Cypress
Debugging techniques
Error handling
Code coverage
Now your PERN stack development workflow is becoming professional, reliable, and production-ready.
Comments
Post a Comment