DEV Community

Play Button Pause Button
Chris
Chris

Posted on

React, Jest, and Testing Library - Quick Overview

This is a quick overview of creating tests using React, Testing Library, and Jest. Below you will find all the code writing for this project.

Styles in App.css

.App {
  margin: 20px;
  font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

App Component in App.js

import './App.css';
import { useState } from 'react';

export const multiplyByTwo = (num) => {
  return num * 2;
};

export default function App() {
  const [value, setValue] = useState(null);
  const total = multiplyByTwo(value);
  const resultsColor = isNaN(total) ? 'red' : 'darkgreen';

  return (
    <div className="App">
      <label htmlFor="value">Enter value</label>
      <input onChange={(e) => setValue(e.target.value)} id="value" />
      <p style={{ color: resultsColor }}>
        {value || 0} * 2 is: {total}
      </p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Tests in App.test.js

import { multiplyByTwo } from './App';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import App from './App';

describe('multiplyByTwo function works correctly', () => {
  test('2 should equal 4', () => {
    expect(multiplyByTwo(2)).toBe(4);
  });
  test('15 should equal 30', () => {
    expect(multiplyByTwo(15)).toBe(30);
  });
});

test('displays correct sum and color for valid input', () => {
  render(<App />);

  const inputElement = screen.getByLabelText(/enter value/i);
  const totalElement = screen.getByText('* 2 is:', { exact: false });

  userEvent.clear(inputElement);
  userEvent.type(inputElement, '50');
  expect(totalElement).toHaveTextContent('100');
  expect(totalElement).toHaveStyle({ color: 'darkgreen' });
});

test('displays red color and NaN for invalid input', () => {
  render(<App />);

  const inputElement = screen.getByLabelText(/enter value/i);
  const totalElement = screen.getByText('* 2 is:', { exact: false });

  userEvent.clear(inputElement);
  userEvent.type(inputElement, 'dwed');
  expect(totalElement).toHaveTextContent('NaN');
  expect(totalElement).toHaveStyle({ color: 'red' });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
saroj8455 profile image
Saroj Padhan

Thank you

Collapse
 
chrislemus profile image
Chris

Sure thing 👍