2nd Episode: Best practices.
Lautaro Suarez
Posted on June 15, 2023
Best practices
During the testing process, our focus is on verifying the desired behaviour rather than specific implementation details.
The Arrange-Act-Assert (AAA) pattern
This widely used pattern helps to ensure that your tests are well-organized and structured correctly. It involves three essential steps: arranging the test environment and setting up any necessary variables, acting by performing the desired action, and asserting that the expected outcome has indeed taken place.
Example:
// Counter.js
import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
Test
// Counter.test.jsx
import { fireEvent, render, screen } from '@testing-library/react';
import Counter from './Counter';
test('increments counter when button is clicked', () => {
// Arrange
render(<Counter />);
const button = screen.getByRole('button');
// Act
fireEvent.click(button);
// Assert
const counterValue = screen.getByText(/1/i);
expect(counterValue).toBeInTheDocument();
});
While it is valuable to follow industry standards, we should also use our judgment to determine when and how to apply them. It's important to aim for tests that closely resemble the behaviour of the code in a production environment.
Posted on June 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.