Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda