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)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay