DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on

2nd Episode: Best practices.

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;
Enter fullscreen mode Exit fullscreen mode

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();
});

Enter fullscreen mode Exit fullscreen mode

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.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay