Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!