Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

148
Vistas
react - how to test a component if it has value prop

App.js

import "./styles.css";

import React, { useState } from "react";
import Input from "./Input";

export default function App() {
  const [value, setValue] = useState("");
  return (
    <div className="App">
      <Input value={value} setValue={setValue} />
    </div>
  );
}

Input.js

import "./styles.css";

export default function Input({ value, setValue }) {
  return (
    <input
      type="text"
      data-testid="input-0"
      value={value}
      onChange={(e) => {
        setValue(e.target.value);
      }}
    />
  );
}

I want to use jest and react-testing-library to test for the <Input> component.

But I cannot figure out how to handle the value prop.

This is the test file I've made, but I cannot go further.

import React, { useState } from "react";
import Input from "@/components/Input/Input";
import userEvent from "@testing-library/user-event";
import { render, screen } from "@testing-library/react";

describe("Testing Input component", () => {
  it("renders a Input", () => {
    const mockSetValue = jest.fn(x => {});
    render(
      <Input
        value={""}
        setValue={(e) => {
          mockSetValue(e)
        }}
      />
    );
    userEvent.type(screen.getByTestId("input-0"), "b");
    expect(screen.getByTestId("input-0")).toHaveValue("b");
  });
});

The test returns failed after I run it.

Codesandbox
https://codesandbox.io/s/affectionate-leftpad-cytmf0?file=/src/Input.jsx:0-219

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

With react-testing-library you want to avoid testing the internal values of components.
Instead you should be checking if the html that's rendered is correct.

In your example: rather than checking whether the value prop is correct, you should check that given a certain value (e.g. "Test Value") the input html element contains the text "Test Value".

Reference: https://testing-library.com/docs/guiding-principles

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda