Testing và Debugging

Dưới đây là hướng dẫn Testing và Debugging trong Node.js theo góc nhìn của Senior Backend Developer, bao gồm unit test, debug, và logging hiệu quả trong môi trường thực tế:


✅ 1. Làm thế nào để thực hiện Unit Test trong Node.js?

Unit test giúp kiểm tra logic độc lập của từng hàm hoặc module.

🔹 Các thư viện phổ biến:

Thư viện

Mục đích

Mocha

Test runner

Chai

Assertion library (expect, should)

Jest

All-in-one testing (runner, assertion, mock, coverage)


🔸 Ví dụ dùng Mocha + Chai

1. Cài đặt:

npm install --save-dev mocha chai

2. Tạo hàm cần test (ví dụ: math.js)

function add(a, b) {
  return a + b;
}
module.exports = { add };

3. Tạo test file (ví dụ: test/math.test.js)

const { expect } = require('chai');
const { add } = require('../math');

describe('Math Utils', () => {
  it('should add two numbers', () => {
    expect(add(2, 3)).to.equal(5);
  });
});

4. Chạy test:

npx mocha

🔸 Ví dụ dùng Jest

1. Cài đặt:

npm install --save-dev jest

2. Định nghĩa test script trong package.json:

"scripts": {
  "test": "jest"
}

3. Viết test file (math.test.js)

const { add } = require('./math');

test('adds two numbers', () => {
  expect(add(1, 2)).toBe(3);
});

4. Chạy test:

npm test

✅ 2. Giới thiệu về cách debug ứng dụng Node.js

🔹 Cách debug:

1. Sử dụng console.log()

  • Cách cơ bản để xem dữ liệu nhưng không chuyên nghiệp.

2. Dùng Node Inspector / Chrome DevTools

node --inspect index.js
  • Truy cập Chrome tại: chrome://inspect → connect → đặt breakpoint như debug JS thông thường.

3. Dùng VSCode Debug

  • Tạo file .vscode/launch.json:

{
  "type": "node",
  "request": "launch",
  "name": "Debug API",
  "program": "${workspaceFolder}/index.js"
}
  • Bấm F5 để debug.


✅ 3. Ghi log ứng dụng trong Node.js bằng Winston & Morgan

🔹 Winston – Ghi log nâng cao, hỗ trợ lưu file, console, custom format...

Cài đặt:

npm install winston

Sử dụng:

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info',
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'logs/app.log' })
  ],
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.printf(({ timestamp, level, message }) => {
      return `${timestamp} ${level}: ${message}`;
    })
  )
});

logger.info('Application started');
logger.error('Something went wrong');

🔹 Morgan – Logging middleware dành cho Express

Cài đặt:

npm install morgan

Tích hợp vào Express:

const express = require('express');
const morgan = require('morgan');

const app = express();

// Log tất cả request ra console
app.use(morgan('dev'));

// Hoặc ghi ra file
const fs = require('fs');
const path = require('path');
const logStream = fs.createWriteStream(path.join(__dirname, 'logs/access.log'), { flags: 'a' });

app.use(morgan('combined', { stream: logStream }));

✅ Tổng kết:

Mục
Công cụ đề xuất

Unit Test

Jest (all-in-one), Mocha + Chai

Debug

VSCode Debug, Chrome Inspector, Node CLI

Logging

Winston (log custom), Morgan (HTTP logs)


Last updated