AAA là cấu trúc chuẩn cho mỗi unit test, giúp test dễ đọc và maintain. Arrange (chuẩn bị): khởi tạo data, mocks, objects cần thiết — đây là phần dài nhất. Act (thực hiện): gọi function/method đang test — chỉ một dòng, test một behavior duy nhất. Assert (kiểm tra kết quả): verify output hoặc side effect.
Ví dụ: // Arrange const cart = new Cart(); cart.addItem({ id: 1, price: 100 }); // Act const total = cart.getTotal(); // Assert expect(total).toBe(100).
AAA is the standard structure for unit tests, making them readable and maintainable. Arrange: set up data, mocks, and objects needed — usually the longest section. Act: call the function/method being tested — single line, testing one behavior. Assert: verify the output or side effects.
- Example:
// Arrangeconst cart = new Cart(); cart.addItem({ id: 1, price: 100 });// Actconst total = cart.getTotal();// Assertexpect(total).toBe(100). - Benefits: clear separation speeds up debugging (bad Arrange → test data issue, bad Act → missing function, bad Assert → logic bug).
- If the Act section has many lines, it signals the function under test has too many responsibilities.
Pitfall: placing expect in the Arrange section blurs boundaries — only assert the final result in the Assert section.