Learn testing strategies and deployment practices for Node.js applications.
Learn testing strategies and deployment practices for Node.js applications.
Learn unit testing with Jest for Node.js applications
Content by: Harsh Zankat
Node.js Developer
Jest is a popular JavaScript testing framework that provides a complete testing solution for Node.js applications. It includes test runners, assertion libraries, mocking capabilities, and code coverage.
// Install Jest
npm install --save-dev jest
// package.json
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
},
"jest": {
"testEnvironment": "node",
"collectCoverageFrom": [
"src/**/*.js",
"!src/**/*.test.js"
],
"coverageThreshold": {
"global": {
"branches": 80,
"functions": 80,
"lines": 80,
"statements": 80
}
}
}
}
// Basic test example
// src/utils/calculator.test.js
const { add, subtract, multiply, divide } = require('./calculator');
describe('Calculator', () => {
test('should add two numbers correctly', () => {
expect(add(2, 3)).toBe(5);
expect(add(-1, 1)).toBe(0);
});
test('should subtract two numbers correctly', () => {
expect(subtract(5, 3)).toBe(2);
expect(subtract(0, 5)).toBe(-5);
});
test('should handle division by zero', () => {
expect(() => divide(5, 0)).toThrow('Division by zero');
});
});
Test your understanding of this topic:
Learn integration testing for Node.js applications
Content by: Prakash Patel
Node.js Developer
Integration testing verifies that different parts of your application work together correctly. It tests the interaction between modules, databases, APIs, and external services.
// Install testing dependencies
npm install --save-dev supertest jest
// test/integration/api.test.js
const request = require('supertest');
const app = require('../../app');
const User = require('../../models/User');
describe('User API Integration Tests', () => {
beforeEach(async () => {
// Clean database before each test
await User.deleteMany({});
});
test('POST /api/users should create a new user', async () => {
const userData = {
name: 'John Doe',
email: 'john@example.com',
password: 'password123'
};
const response = await request(app)
.post('/api/users')
.send(userData)
.expect(201);
expect(response.body.success).toBe(true);
expect(response.body.data.name).toBe(userData.name);
expect(response.body.data.email).toBe(userData.email);
});
test('GET /api/users should return all users', async () => {
// Create test users
await User.create([
{ name: 'User 1', email: 'user1@example.com', password: 'password' },
{ name: 'User 2', email: 'user2@example.com', password: 'password' }
]);
const response = await request(app)
.get('/api/users')
.expect(200);
expect(response.body.success).toBe(true);
expect(response.body.data).toHaveLength(2);
});
test('PUT /api/users/:id should update user', async () => {
const user = await User.create({
name: 'Original Name',
email: 'original@example.com',
password: 'password'
});
const updateData = { name: 'Updated Name' };
const response = await request(app)
.put(`/api/users/${user._id}`)
.send(updateData)
.expect(200);
expect(response.body.data.name).toBe(updateData.name);
});
});
Test your understanding of this topic:
Learn to containerize Node.js applications using Docker
Content by: Sachin Patel
Node.js Developer
Docker is a platform for developing, shipping, and running applications in containers. It provides a consistent environment across different machines and makes deployment easier.
# Use official Node.js runtime as base image
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --only=production
# Copy application code
COPY . .
# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nextjs -u 1001
# Change ownership
RUN chown -R nextjs:nodejs /app
USER nextjs
# Expose port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:3000/health || exit 1
# Start application
CMD ["npm", "start"]
# Docker Compose example
# docker-compose.yml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- MONGODB_URI=mongodb://mongo:27017/myapp
depends_on:
- mongo
restart: unless-stopped
mongo:
image: mongo:5.0
ports:
- "27017:27017"
volumes:
- mongo_data:/data/db
restart: unless-stopped
volumes:
mongo_data:
Test your understanding of this topic:
Learn to deploy Node.js applications to cloud platforms
Content by: Harsh Zankat
Node.js Developer
Cloud deployment involves hosting your Node.js application on cloud platforms like AWS, Google Cloud, or Azure. This includes container orchestration, load balancing, and auto-scaling.
# Deploy to AWS ECS using Docker
# 1. Build and push Docker image
docker build -t my-nodejs-app .
docker tag my-nodejs-app:latest 123456789.dkr.ecr.us-east-1.amazonaws.com/my-nodejs-app:latest
docker push 123456789.dkr.ecr.us-east-1.amazonaws.com/my-nodejs-app:latest
# 2. Create ECS task definition
{
"family": "my-nodejs-app",
"networkMode": "awsvpc",
"requiresCompatibilities": ["FARGATE"],
"cpu": "256",
"memory": "512",
"executionRoleArn": "arn:aws:iam::123456789:role/ecsTaskExecutionRole",
"containerDefinitions": [
{
"name": "my-nodejs-app",
"image": "123456789.dkr.ecr.us-east-1.amazonaws.com/my-nodejs-app:latest",
"portMappings": [
{
"containerPort": 3000,
"protocol": "tcp"
}
],
"environment": [
{
"name": "NODE_ENV",
"value": "production"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/my-nodejs-app",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "ecs"
}
}
}
]
}
# 3. Deploy using AWS CLI
aws ecs create-service \
--cluster my-cluster \
--service-name my-nodejs-app \
--task-definition my-nodejs-app:1 \
--desired-count 2 \
--launch-type FARGATE \
--network-configuration "awsvpcConfiguration={subnets=[subnet-12345],securityGroups=[sg-12345],assignPublicIp=ENABLED}"
Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Continue to Module 7