Testing với React Testing Library và Jest

Tạo bởi Hoàng Vũ, chỉnh sửa cuối lúc 11 tháng 4, 2025

Testing là một phần quan trọng trong quy trình phát triển phần mềm hiện đại, giúp đảm bảo ứng dụng hoạt động đúng như kỳ vọng và giảm thiểu lỗi. Trong bài học này, bạn sẽ học cách thiết lập môi trường test với Jest và React Testing Library, viết unit test cho các component, và kiểm tra hành vi người dùng như click, nhập liệu, điều hướng. Bạn cũng sẽ biết cách mock API hoặc state khi test logic phức tạp.

Testing với React Testing Library và Jest

1. Cài đặt Jest và React Testing Library trong dự án Next.js

Đầu tiên, cài đặt các package cần thiết:

npm install --save-dev jest @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom

Thêm file cấu hình jest.config.js:

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

module.exports = createJestConfig({
  testEnvironment: 'jest-environment-jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
});

Tạo file jest.setup.js:

import '@testing-library/jest-dom';

Cập nhật package.json:

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

2. Viết unit test cho component đơn giản

Giả sử bạn có một component Button.tsx:

const Button = ({ label }: { label: string }) => {
  return <button>{label}</button>;
};

export default Button;

Viết file test Button.test.tsx:

import { render, screen } from '@testing-library/react';
import Button from './Button';

test('render button with label', () => {
  render(<Button label="Click me" />);
  expect(screen.getByText('Click me')).toBeInTheDocument();
});

3. Mock API hoặc state khi test logic component

Ví dụ test một component fetch dữ liệu:

import { useEffect, useState } from 'react';

export function PostTitle() {
  const [title, setTitle] = useState('');

  useEffect(() => {
    fetch('/api/post')
      .then((res) => res.json())
      .then((data) => setTitle(data.title));
  }, []);

  return <h1>{title}</h1>;
}

File test PostTitle.test.tsx:

import { render, screen, waitFor } from '@testing-library/react';
import { PostTitle } from './PostTitle';

beforeEach(() => {
  global.fetch = jest.fn(() =>
    Promise.resolve({
      json: () => Promise.resolve({ title: 'Hello World' }),
    })
  );
});

test('render fetched title', async () => {
  render(<PostTitle />);
  await waitFor(() => expect(screen.getByText('Hello World')).toBeInTheDocument());
});

4. Viết test kiểm tra hành vi người dùng

Giả sử có một form đơn giản:

function LoginForm() {
  const [name, setName] = useState('');
  return (
    <form>
      <input placeholder="Name" onChange={(e) => setName(e.target.value)} />
      <button disabled={!name}>Submit</button>
    </form>
  );
}

Viết test LoginForm.test.tsx:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import LoginForm from './LoginForm';

test('enable submit when input has value', async () => {
  render(<LoginForm />);
  const input = screen.getByPlaceholderText('Name');
  const button = screen.getByRole('button');

  expect(button).toBeDisabled();

  await userEvent.type(input, 'John');
  expect(button).not.toBeDisabled();
});

Kết luận

Việc viết test không chỉ giúp phát hiện lỗi sớm, mà còn giúp bạn refactor code tự tin hơn và nâng cao chất lượng phần mềm. Với Jest và React Testing Library, bạn có thể:

  • Kiểm tra component hiển thị đúng
  • Test hành vi tương tác như click, input, submit
  • Mô phỏng dữ liệu từ API hoặc context

Đây là nền tảng vững chắc để bạn xây dựng các ứng dụng Next.js ổn định, dễ bảo trì và đáng tin cậy trong môi trường production.

Website Logo

Với hơn 10 năm kinh nghiệm lập trình web và từng làm việc với nhiều framework, ngôn ngữ như PHP, JavaScript, React, jQuery, CSS, HTML, CakePHP, Laravel..., tôi hy vọng những kiến thức được chia sẻ tại đây sẽ hữu ích và thiết thực cho các bạn.

Bình luận

Website Logo

Chào, tôi là Vũ. Đây là blog hướng dẫn lập trình của tôi.

Liên hệ công việc qua email dưới đây.

lhvuctu@gmail.com

Chúng Tôi Trên

Bạn đang muốn học về lập trình website?

Bạn cần nâng cao kiến thức chuyên nghiệp hơn để nâng cao cơ hội nghề nghiệp? Liên hệ