App.js
JavaScript
x
14
14
1
import "./styles.css";
2
3
import React, { useState } from "react";
4
import Input from "./Input";
5
6
export default function App() {
7
const [value, setValue] = useState("");
8
return (
9
<div className="App">
10
<Input value={value} setValue={setValue} />
11
</div>
12
);
13
}
14
Input.js
JavaScript
1
15
15
1
import "./styles.css";
2
3
export default function Input({ value, setValue }) {
4
return (
5
<input
6
type="text"
7
data-testid="input-0"
8
value={value}
9
onChange={(e) => {
10
setValue(e.target.value);
11
}}
12
/>
13
);
14
}
15
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.
JavaScript
1
21
21
1
import React, { useState } from "react";
2
import Input from "@/components/Input/Input";
3
import userEvent from "@testing-library/user-event";
4
import { render, screen } from "@testing-library/react";
5
6
describe("Testing Input component", () => {
7
it("renders a Input", () => {
8
const mockSetValue = jest.fn(x => {});
9
render(
10
<Input
11
value={""}
12
setValue={(e) => {
13
mockSetValue(e)
14
}}
15
/>
16
);
17
userEvent.type(screen.getByTestId("input-0"), "b");
18
expect(screen.getByTestId("input-0")).toHaveValue("b");
19
});
20
});
21
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