I have the following Form
component with two nested components (Input
and Greeting
):
import React from 'react';
export default function Form() {
return (
<div>
<p>Form</p>
<Greeting />
<Input label="first name" id="firstname" />
<Input label="last name" id="lastname" />
</div>
);
}
function Input({ label, id }: { label:string, id:string }) {
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} />
</div>
);
}
function Greeting() {
return <div>Hello</div>;
}
And I have this Jest and @testing-library/react
test:
test('All input fields are displayed', allFieldsAreDisplayed);
test('Greeting displayed', greetingDisplayed);
function allFieldsAreDisplayed() {
render(<Form />);
const firstNameInput = screen.getByText('first name');
expect(firstNameInput).toBeInTheDocument();
}
function greetingDisplayed() {
render(<Form />);
const greeting = screen.getByText('Hello');
expect(greeting).toBeInTheDocument();
}
However, when I run the test to see if both are displayed, I get the below error messages:
TestingLibraryElementError: Unable to find an element with the text: first name. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, <script />, <style />
<body />
12 | function allFieldsAreDisplayed() {
13 | render(<Form />);
> 14 | const firstNameInput = screen.getByText('first name');
| ^
15 | expect(firstNameInput).toBeInTheDocument();
16 | }
17 |
And:
TestingLibraryElementError: Unable to find an element with the text: Hello. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, <script />, <style />
<body />
18 | function greetingDisplayed() {
19 | render(<Form />);
> 20 | const greeting = screen.getByText('Hello');
| ^
21 | expect(greeting).toBeInTheDocument();
22 | }
23 |