Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 34: Testing trong NestJS

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 trong NestJS. TaskFlow API đã có JWT, phân quyền, cache, upload: sửa code xong mà curl lại từng thứ thì rất dễ sót.

1. Vitest trong NestJS.

Từ NestJS 12, project ESM tạo bằng nest new dùng Vitest (project CommonJS vẫn dùng Jest). TaskFlow đã có sẵn từ Bài 3: Vitest 4, Supertest, @nestjs/testing và các script:

npm test              # unit test: file *.spec.ts nằm cạnh code trong src/
npm run test:cov      # kèm báo cáo coverage (thư mục coverage/)
npm run test:e2e      # e2e test: file *.e2e-spec.ts trong test/

Unit test kiểm tra riêng một class, dependency thay bằng mock. E2e test khởi động cả ứng dụng, gửi request HTTP như client thật. Cấu hình có globals: true nên describe, it, expect, vi không cần import.

2. Unit test service với mock.

Test.createTestingModule() nhận metadata như @Module(), compile() dựng module với DI như lúc chạy thật. Thay cho PrismaService thật, mình đưa vào object mock bằng useValue (Bài 6):

- src/projects/projects.service.spec.ts (đoạn trích, bỏ phần import và test thứ ba)

describe('ProjectsService', () => {
    let service: ProjectsService;
    // Chỉ mock các method mà test gọi tới
    const prisma = {
        project: { findUnique: vi.fn(), count: vi.fn() },
        task: { groupBy: vi.fn() },
    };
    const cache = { get: vi.fn(), set: vi.fn() };

    beforeEach(async () => {
        vi.resetAllMocks(); // xoá lời gọi và giá trị trả về của test trước
        const moduleRef = await Test.createTestingModule({
            providers: [
                ProjectsService,
                { provide: PrismaService, useValue: prisma },
                { provide: CACHE_MANAGER, useValue: cache },
                { provide: ActivitiesService, useValue: { log: vi.fn() } },
                { provide: AttachmentsService, useValue: {} },
            ],
        }).compile();
        service = moduleRef.get(ProjectsService);
    });

    it('findOne() chỉ tìm project của user đang đăng nhập', async () => {
        prisma.project.findUnique.mockResolvedValue(null);

        await expect(service.findOne(1, 2)).rejects.toThrow(
            ProjectNotFoundException,
        );
        expect(prisma.project.findUnique).toHaveBeenCalledWith(
            expect.objectContaining({ where: { id: 1, ownerId: 2 } }),
        );
    });

    it('stats() có cache thì không query database', async () => {
        const cached = { projectId: 1, total: 3 };
        cache.get.mockResolvedValue(cached);

        await expect(service.stats(1, 2)).resolves.toBe(cached);
        // Key có id của user: mỗi user một bản cache riêng
        expect(cache.get).toHaveBeenCalledWith('stats:user:2:project:1');
        expect(prisma.task.groupBy).not.toHaveBeenCalled();
    });
});

Trong đó:

  • vi.fn() tạo hàm mock ghi lại mọi lời gọi, mockResolvedValue(x) cho nó trả về Promise của x.
  • rejects.toThrow() kiểm tra exception, toHaveBeenCalledWith() kiểm tra tham số mock đã nhận.

Hai test giữ điều kiện sở hữu (Bài 21) và key cache theo user (Bài 27): ai lỡ sửa mất là test đỏ. Class nhiều dependency thì dùng .useMocker(() => ({ findAll })) để mock mọi dependency chưa khai báo. Project còn có test cho RolesGuard và UserCacheInterceptor.

npm test
# ...
#  Test Files  5 passed (5)
#       Tests  9 passed (9)

3. E2e test với database riêng.

File test/app.e2e-spec.ts do CLI sinh có hai vấn đề: AppModule đọc .env nên test chạy trên database dev, và createNestApplication() không chạy main.ts (không có global prefix, ValidationPipe, filter).

Mình chuyển phần cấu hình của main.ts sang src/app.setup.ts để main.ts và test cùng dùng:

- src/app.setup.ts (đoạn trích, bỏ phần import)

export const appOptions: NestApplicationOptions = {
    routeConflictPolicy: { duplicate: 'error' },
    routeResolutionStrategy: 'specificity',
};

// Dùng chung cho main.ts và e2e test: test chạy với đúng cấu hình của app thật
export function configureApp(app: INestApplication): void {
    // ... chuyển nguyên từ main.ts: prefix, versioning, pipe, filter,
    // middleware requestId, interceptor, WebSocket adapter
}

main.ts giờ tạo app với ...appOptions rồi gọi configureApp(app). Database thì e2e test dùng file .env.test (không có secret thật nên được commit):

- .env.test (đoạn trích)

DATABASE_URL="postgresql://taskflow:taskflow@localhost:5432/taskflow_test?schema=public"
MONGODB_URI="mongodb://taskflow:taskflow@localhost:27017/taskflow_test?authSource=admin"
# Redis database số 1 (dev dùng số 0 mặc định)
REDIS_URL="redis://localhost:6379/1"

Option env của Vitest nạp file này vào process.env, mà ConfigModule ưu tiên process.env hơn .env (Bài 14):

- vitest.config.e2e.ts

import { readFileSync } from 'node:fs';
import { parseEnv } from 'node:util';
import { defineConfig } from 'vitest/config';

export default defineConfig({
  resolve: { tsconfigPaths: true },
  test: {
    globals: true,
    root: './',
    include: ['**/*.e2e-spec.ts'],
    // Biến trong .env.test ghi đè .env: không chạm database dev
    env: parseEnv(readFileSync('.env.test', 'utf8')),
    globalSetup: './test/global-setup.ts',
    // Các file dùng chung database test: chạy lần lượt, không song song
    fileParallelism: false,
    hookTimeout: 30_000, // beforeAll khởi động cả AppModule
  },
});

- test/global-setup.ts

import { execSync } from 'node:child_process';
import { Redis } from 'ioredis';
import mongoose from 'mongoose';
import type { TestProject } from 'vitest/node';

// Chạy một lần trước mọi file e2e: đưa 3 database test về trạng thái trống
export default async function setup(project: TestProject): Promise<void> {
    const env = { ...process.env, ...project.config.env };
    const { DATABASE_URL = '', MONGODB_URI = '', REDIS_URL = '' } = env;
    // Chốt an toàn: nhầm cấu hình thì dừng, không xoá database dev
    if (
        !new URL(DATABASE_URL).pathname.endsWith('_test') ||
        !new URL(MONGODB_URI).pathname.endsWith('_test') ||
        new URL(REDIS_URL).pathname !== '/1'
    ) {
        throw new Error('E2e test chỉ chạy trên database test (.env.test)');
    }
    // Chưa có database thì tạo, có rồi thì xoá sạch và chạy lại mọi migration
    execSync('npx prisma migrate reset --force', { env, stdio: 'inherit' });
    await mongoose.connect(MONGODB_URI);
    await mongoose.connection.dropDatabase();
    await mongoose.disconnect();
    const redis = new Redis(REDIS_URL);
    await redis.flushdb(); // chỉ xoá database số 1
    await redis.quit();
}

Lưu ý: Chỉ database được tách, file upload vẫn ghi vào storage/attachments như lúc dev. Test upload tự xoá file của nó, nhưng test hỏng giữa chừng có thể để lại file.

Hàm dựng app cho các file e2e dùng overrideProvider() thay NotificationsService bằng mock (không cần NATS), kèm hàm đăng ký và đăng nhập lấy token:

- test/create-test-app.ts (bỏ phần import)

// Thay NotificationsService: test không gửi message qua NATS, chỉ ghi lại lời gọi
export const notifications = {
    sendWelcome: vi.fn(),
    sendTaskAssigned: vi.fn(),
};

// Toàn bộ AppModule với database test, cấu hình giống hệt main.ts
export async function createTestApp(): Promise<INestApplication<App>> {
    const moduleRef = await Test.createTestingModule({
        imports: [AppModule],
    })
        .overrideProvider(NotificationsService)
        .useValue(notifications)
        .compile();
    const app =
        moduleRef.createNestApplication<INestApplication<App>>(appOptions);
    configureApp(app);
    await app.init();
    return app;
}

// Đăng ký rồi đăng nhập, trả về giá trị cho header Authorization
export async function registerAndLogin(
    app: INestApplication<App>,
    name: string,
    email: string,
): Promise<string> {
    const user = { name, email, password: 'matkhau123' };
    await request(app.getHttpServer())
        .post('/api/v1/auth/register')
        .send(user)
        .expect(201);
    const res = await request(app.getHttpServer())
        .post('/api/v1/auth/login')
        .send({ email, password: user.password })
        .expect(200);
    return `Bearer ${res.body.data.accessToken}`;
}

4. Test xác thực và phân quyền.

Trong beforeAll, tai và An đăng ký, tai tạo một project. An đụng vào project đó phải nhận 404 (Bài 21), ở cả REST lẫn GraphQL:

- test/projects.e2e-spec.ts (đoạn trích, bỏ phần import)

describe('Projects (e2e)', () => {
    let app: INestApplication<App>;
    let tai: string; // header Authorization của chủ project
    let an: string; // user thứ hai
    let id: number; // project do tai tạo
    let url: string;

    beforeAll(async () => {
        app = await createTestApp();
        tai = await registerAndLogin(app, 'Tai', '[email protected]');
        an = await registerAndLogin(app, 'An', '[email protected]');
        const res = await request(app.getHttpServer())
            .post('/api/v1/projects')
            .set('Authorization', tai)
            .send({ name: 'TaskFlow API' })
            .expect(201);
        id = res.body.data.id;
        url = `/api/v1/projects/${id}`;
    });

    // ... afterAll() đóng app, test 401

    it('user khác không xem, sửa, xoá được project: 404', async () => {
        const server = app.getHttpServer();
        await request(server).get(url).set('Authorization', an).expect(404);
        await request(server)
            .patch(url)
            .set('Authorization', an)
            .send({ name: 'Của An' })
            .expect(404);
        await request(server).delete(url).set('Authorization', an).expect(404);
    });

    // ...
});

request(app.getHttpServer()) gửi request vào app mà không cần chạy server ở cổng 3000. Test GraphQL gửi mutation updateProject tới /graphql: lỗi nằm trong mảng errors (Bài 24), status HTTP vẫn là 200.

Các test khác kiểm tra: không có token hay token sai 401 (Bài 20), gửi null hay field lạ ownerId 400, An đọc thống kê tai vừa cache 404, user thường xoá nhật ký 403, đăng nhập quá 5 lần/phút 429, file chữ đổi đuôi .png 400. Chạy khi PostgreSQL, MongoDB, Redis đang bật:

npm run test:e2e
# PostgreSQL database taskflow_test created at localhost:5432
# ...
#  Test Files  4 passed (4)
#       Tests  15 passed (15)

Test chỉ có ích khi nó đỏ lúc code sai: mình thử xoá ownerId khỏi findOne() và tắt forbidNonWhitelisted, ba test báo lỗi ngay.

5. Lời kết.

Như vậy mình đã giới thiệu xong testing trong NestJS: unit test với mock và Test.createTestingModule(), e2e test bằng Supertest trên database riêng cho TaskFlow API. Bài sau mình sẽ giới thiệu về health check với Terminus trong NestJS.

Đă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