Unit.js là framework unit testing đa nền tảng, mã nguồn mở, hỗ trợ nhiều style: TDD, BDD, spec. Chạy trên Node.js và trình duyệt.
Cài đặt
npm install unit.js --save-dev
Ví dụ cơ bản (BDD style)
const test = require('unit.js');
test.string('Welcome')
.isEqualTo('Welcome')
.isIdenticalTo('Welcome')
.startsWith('Wel')
.endsWith('come');
Cấu trúc test suite
test.describe('User Authentication', function() {
test.it('should hash password correctly', function() {
const hashed = hashPassword('secret123');
test.string(hashed).isNotEqualTo('secret123');
test.string(hashed).match(/^\$2[aby]\$\d+\$/); // bcrypt pattern
});
test.it('should reject short password', function() {
test.exception(function() {
hashPassword('123');
}).hasMessage('Password too short');
});
});
Chạy test
# package.json
"scripts": {
"test": "node node_modules/unit.js/bin/unit.js test/**/*.test.js"
}
So sánh với các framework phổ biến (2024)
| Framework | Đặc điểm | Phù hợp |
|---|---|---|
| Vitest | Nhanh,兼容 Jest API, native ESM, Vite integration | Dự án hiện đại, Vite/React/Vue/Svelte |
| Jest | Mature, snapshot, coverage built-in, large ecosystem | Enterprise, React, large codebase |
| Mocha + Chai | Flexible, nhiều assertion style, cần config thêm | Legacy, Node.js backend |
| Unit.js | Fluent API, browser + Node, ít dependency | Simple project, học tập |
Khuyến nghị: Dự án mới dùng Vitest hoặc Jest. Unit.js phù hợp cho bài học, demo nhỏ.