Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 24: Testing ứng dụng Express

Đến bài trước, mỗi lần sửa code chúng ta lại mở trình duyệt hoặc gõ curl để thử. Tiếp tục với series, bài này mình sẽ giới thiệu với mọi người về testing ứng dụng Express: viết code để tự kiểm tra MiniBlog, chạy lại chỉ bằng một lệnh.

1. Test runner có sẵn của Node.js.

Node.js có sẵn module node:test để viết test và lệnh node --test để chạy, không cần cài Jest hay Mocha. Mỗi test là một hàm dùng node:assert/strict so sánh kết quả, sai thì assert ném lỗi và test fail.

VD: Mình test hai hàm không cần database là slugify() (Bài 10) và parseListQuery() (Bài 21).

- test/lib.test.js

import { test } from 'node:test';
import assert from 'node:assert/strict';
import slugify from '../lib/slugify.js';
import { parseListQuery } from '../lib/pagination.js';

test('slugify bỏ dấu tiếng Việt', () => {
    assert.equal(slugify('Đăng nhập trong Express 5'), 'dang-nhap-trong-express-5');
});

test('parseListQuery tính offset và giới hạn limit', () => {
    const query = parseListQuery({ page: '3', limit: '100' }, { perPage: 10, maxPerPage: 50 });
    assert.deepEqual(query, {
        filters: { search: '', authorId: null },
        page: 3,
        limit: 50,
        offset: 100,
    });
});

assert.equal() so sánh hai giá trị (như ===), còn assert.deepEqual() so sánh từng trường của object. Chạy thử:

node --test test/lib.test.js
# ✔ slugify bỏ dấu tiếng Việt (22.576054ms)
# ✔ parseListQuery tính offset và giới hạn limit (5.464262ms)
# ℹ tests 2
# ℹ pass 2
# ... (rút gọn)

2. Chuẩn bị database riêng cho test.

Test sẽ xoá và tạo lại dữ liệu nên không được chạy trên database miniblog đang dùng. Mình tạo database miniblog_test trong container MySQL của Bài 12 và cài supertest (bản 7.3.2) để gửi request tới app:

docker exec miniblog-mysql mysql -u root -prootsecret --default-character-set=utf8mb4 \
    -e "CREATE DATABASE miniblog_test; GRANT ALL ON miniblog_test.* TO 'miniblog'@'%'"
npm install -D supertest

Cấu hình khi test để trong file riêng, không có bí mật thật nên commit cùng code được:

- .env.test

# Cấu hình khi chạy test (npm test): database riêng, không có bí mật thật
NODE_ENV=test
DB_HOST=localhost
DB_PORT=3306
DB_USER=miniblog
DB_PASSWORD=secret
DB_NAME=miniblog_test
SESSION_SECRET=session-secret-chi-dung-khi-chay-test-01
JWT_SECRET=jwt-secret-chi-dung-khi-chay-test-000001
APP_URL=http://localhost:3000
SMTP_HOST=127.0.0.1
SMTP_PORT=1025
MAIL_FROM="MiniBlog <[email protected]>"

NODE_ENV=test làm logger ở mức silent (Bài 23) nên kết quả test không lẫn log request. Thêm hai script vào package.json:

"pretest": "node --env-file=.env.test database/migrate.js",
"test": "node --env-file=.env.test --test --test-concurrency=1 --test-force-exit test/*.test.js"

Trong đó:

  • pretest được npm tự chạy trước test: chạy migration (Bài 14) cho miniblog_test.
  • Mỗi file test chạy trong một process riêng và mặc định nhiều file chạy song song. Các file dùng chung một database nên --test-concurrency=1 cho chạy lần lượt, kẻo file này xoá dữ liệu của file kia.
  • Pool MySQL còn giữ kết nối, session store còn timer dọn session nên process không tự thoát, --test-force-exit cho thoát luôn khi hết test.

3. Test route có database với supertest.

- test/helpers.js

import pool from '../lib/db.js';
import { register } from '../services/auth-service.js';

// Tác giả có sẵn trong database test
export const AUTHOR = { name: 'Tác giả Test', email: '[email protected]', password: 'matkhau123' };

// Xoá sạch dữ liệu rồi tạo lại tác giả, mỗi file test gọi một lần ở before()
export async function resetDatabase() {
    // Chặn chạy nhầm vào database đang dùng để phát triển
    if (process.env.DB_NAME !== 'miniblog_test') {
        throw new Error('Test chỉ được chạy với database miniblog_test');
    }
    await pool.query('DELETE FROM sessions');
    await pool.query('DELETE FROM posts'); // bình luận bị xoá theo
    await pool.query('DELETE FROM users');
    await register(AUTHOR);
}

request(app) của supertest tự mở app ở một cổng ngẫu nhiên, không cần npm run start. Test import app.js nên lib/env.js vẫn kiểm tra biến môi trường:

- test/pages.test.js

import { describe, it, before } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import app from '../app.js';
import { resetDatabase } from './helpers.js';
import { createPost } from '../services/post-service.js';

describe('Trang web', () => {
    before(async () => {
        await resetDatabase();
        await createPost({ title: 'Testing trong Express', content: 'Bài viết dùng để chạy thử bộ test.' });
    });

    it('trang chủ hiện bài viết mới', async () => {
        const res = await request(app).get('/').expect(200);
        assert.match(res.text, /Testing trong Express/);
    });

    it('xem được bài viết theo slug', async () => {
        await request(app).get('/posts/testing-trong-express').expect(200);
    });

    it('bài viết không có thì trả về 404', async () => {
        const res = await request(app).get('/posts/khong-co').expect(404);
        assert.match(res.text, /Không tìm thấy bài viết/);
    });
});

Trong đó:

  • describe() gom các test thành một nhóm, it() là tên khác của test(). Hàm truyền cho before() chạy một lần trước các test trong nhóm.
  • .expect(200) kiểm tra status code. res.text là body HTML, res.body là JSON đã parse.

4. Test đăng nhập.

Form đăng nhập (Bài 16) cần cookie session và token CSRF (Bài 17). request.agent(app) giữ cookie giữa các request như trình duyệt, token thì mình lấy từ HTML của form:

- test/auth.test.js

import { describe, it, before } from 'node:test';
import request from 'supertest';
import app from '../app.js';
import { resetDatabase, AUTHOR } from './helpers.js';

describe('Đăng nhập', () => {
    before(resetDatabase);

    it('chưa đăng nhập thì bị chuyển tới /login', async () => {
        await request(app).get('/posts/new').expect(303).expect('Location', '/login');
    });

    it('đăng nhập đúng thì vào được trang viết bài', async () => {
        const agent = request.agent(app); // giữ cookie giữa các request như trình duyệt
        const form = await agent.get('/login').expect(200);
        const csrf = form.text.match(/name="_csrf" value="([^"]+)"/)[1]; // token CSRF trong form
        await agent.post('/login').type('form')
            .send({ _csrf: csrf, email: AUTHOR.email, password: AUTHOR.password })
            .expect(303)
            .expect('Location', '/');
        await agent.get('/posts/new').expect(200);
    });

    it('không có token CSRF thì trả về 403', async () => {
        await request(app).post('/login').type('form')
            .send({ email: AUTHOR.email, password: AUTHOR.password })
            .expect(403);
    });
});

Supertest không tự đi theo redirect, nên kiểm tra được status 303 và header Location. .type('form') gửi body dạng form như trình duyệt.

5. Test REST API.

API dùng token (Bài 20) nên chỉ cần lấy token một lần ở before() rồi gửi kèm header Authorization:

- test/api.test.js

import { describe, it, before } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import app from '../app.js';
import { resetDatabase, AUTHOR } from './helpers.js';

describe('API bài viết', () => {
    const post = { title: 'Bài viết qua API', content: 'Nội dung bài viết được tạo bằng API.' };
    let token;

    before(async () => {
        await resetDatabase();
        const res = await request(app).post('/api/v1/auth/token')
            .send({ email: AUTHOR.email, password: AUTHOR.password })
            .expect(200);
        token = res.body.data.accessToken;
    });

    it('không có token thì trả về 401', async () => {
        await request(app).post('/api/v1/posts').send(post)
            .expect(401)
            .expect('WWW-Authenticate', 'Bearer');
    });

    it('dữ liệu sai thì trả về 422 kèm lỗi', async () => {
        const res = await request(app).post('/api/v1/posts')
            .set('Authorization', `Bearer ${token}`)
            .send({ title: 'API', content: post.content })
            .expect(422);
        assert.equal(res.body.errors.title, 'Tiêu đề phải từ 5 đến 150 ký tự');
    });

    it('có token thì tạo được bài viết', async () => {
        const res = await request(app).post('/api/v1/posts')
            .set('Authorization', `Bearer ${token}`)
            .send(post)
            .expect(201)
            .expect('Location', '/api/v1/posts/bai-viet-qua-api');
        assert.equal(res.body.data.title, post.title);

        const list = await request(app).get('/api/v1/posts').expect(200);
        assert.equal(list.body.meta.total, 1);
    });
});

Chạy cả bộ test (rút gọn):

npm test
# Database đã cập nhật
# ▶ API bài viết
#   ✔ không có token thì trả về 401 (17.771264ms)
#   ✔ dữ liệu sai thì trả về 422 kèm lỗi (26.506687ms)
#   ✔ có token thì tạo được bài viết (35.22786ms)
# ✔ API bài viết (313.786259ms)
# ...
# ℹ tests 11
# ℹ pass 11
# ℹ fail 0

Test sai thì có dấu ✖ và lý do, VD đổi .expect(404) trong pages.test.js thành .expect(200) (thử xong nhớ đổi lại):

# ✖ bài viết không có thì trả về 404 (21.55671ms)
#   Error: expected 200 "OK", got 404 "Not Found"

Test chỉ đụng tới miniblog_test, dữ liệu của npm run dev vẫn giữ nguyên, không cần npm run db:seed.

Code đầy đủ của MiniBlog sau bài này nằm ở tag bai-24 trên GitHub; các thay đổi của riêng bài này: so sánh bai-23...bai-24.

6. Lời kết.

Như vậy là chúng ta đã xong testing ứng dụng Express: test hàm bằng node:test, test route, đăng nhập và API bằng supertest trên một database riêng. Bài sau, cũng là bài cuối của series, mình sẽ giới thiệu với mọi người về deploy ứng dụng Express lên server.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha