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
Advertisement
Answer
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