Testing

Testing là quá trình kiểm tra code để đảm bảo nó hoạt động đúng như mong đợi. Đây là kỹ năng quan trọng trong phát triển phần mềm chuyên nghiệp.

✅ Testing là gì?

Testing giúp bạn:

  • Tìm và sửa lỗi sớm
  • Đảm bảo code hoạt động đúng
  • Tăng tự tin khi refactor
  • Cải thiện chất lượng code

🎬 Video hướng dẫn

🖼️ Hình ảnh minh họa

Testing

📚 Các loại testing

1. Unit Testing

Kiểm tra từng function/component riêng lẻ:

1
2
3
4
5
6
// sum.test.js
import { sum } from "./sum";

test("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});

2. Integration Testing

Kiểm tra sự tương tác giữa các component:

1
2
3
4
5
6
7
import { render, screen } from "@testing-library/react";
import UserProfile from "./UserProfile";

test("renders user profile", () => {
  render(<UserProfile user={{ name: "John" }} />);
  expect(screen.getByText("John")).toBeInTheDocument();
});

3. End-to-End (E2E) Testing

Kiểm tra toàn bộ flow của ứng dụng:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Cypress example
describe("Login Flow", () => {
  it("should login successfully", () => {
    cy.visit("/login");
    cy.get("[data-cy=email]").type("user@example.com");
    cy.get("[data-cy=password]").type("password");
    cy.get("[data-cy=submit]").click();
    cy.url().should("include", "/dashboard");
  });
});

🛠️ Testing Tools

Jest

1
2
3
4
5
// Jest configuration
module.exports = {
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
};

React Testing Library

1
2
3
4
5
6
7
8
9
import { render, screen, fireEvent } from "@testing-library/react";
import Button from "./Button";

test("button click", () => {
  const handleClick = jest.fn();
  render(<Button onClick={handleClick} />);
  fireEvent.click(screen.getByRole("button"));
  expect(handleClick).toHaveBeenCalledTimes(1);
});

Cypress

1
2
3
4
5
6
7
// cypress/integration/app.spec.js
describe("App", () => {
  it("should load homepage", () => {
    cy.visit("/");
    cy.contains("Welcome");
  });
});

💡 Best Practices

  • Viết test trước khi code (TDD)
  • Test behavior, không test implementation
  • Giữ test đơn giản và dễ đọc
  • Test edge cases
  • Maintain test coverage > 80%

💪 Thực hành

  1. Viết unit tests cho functions
  2. Test React components
  3. Setup E2E testing với Cypress
  4. Đạt test coverage cao

🔗 Tài nguyên

➡️ Bước tiếp theo

Sau khi nắm vững Testing, hãy học Deployment!