I've been trying to solve this all day. I've been all over the Testing Library documentation and have tried many solutions. The closest I could get is with the test code posted below.
CreatePost.js
import React, { useState } from 'react';
import axios from 'axios';
export default () => {
const [title, setTitle] = useState('');
const onSubmit = async event => {
event.preventDefault();
await axios.post('http://localhost:4000/posts', {
title
});
// clear title
setTitle('');
};
return (
<div>
<form onSubmit={onSubmit} data-testid="form">
<div className="form-group">
<label htmlFor="titleInput">Title</label>
<input
data-testid="title"
id="titleInput"
type="text"
name="title"
placeholder="Title"
value={title}
onChange={e => setTitle(e.target.value)}
className="form-control"
/>
</div>
<button className="btn btn-primary">Submit</button>
</form>
</div>
);
};
CreatePost.test.js
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import CreatePost from '../CreatePost';
it("Inputs should have the correct value", () => {
const { getByLabelText } = render(<CreatePost />)
const input = getByLabelText(/title/i)
fireEvent.change(input, { target: { value: "Lorem ipsum dolor sit amet, consectetur..." } })
expect(screen.getByRole(/title/i)).toHaveTextContent('Lorem ipsum dolor sit amet, consectetur....')
})
This is the only test I've tried that will fire the onChange event for the input as the console output shows that the value was updated. However, my expect
statement is not able to find the element. So why does it fire the onChange event, but cannot be found?
Console Error
FAIL src/__test__/CreatePost.test.js
● Inputs should have the correct value
TestingLibraryElementError: Unable to find an accessible element with the role "/title/i"
Here are the accessible roles:
textbox:
Name "Title":
<input
class="form-control"
data-testid="title"
id="titleInput"
name="title"
placeholder="Title"
type="text"
value="Lorem ipsum dolor sit amet, consectetur..."
/>
--------------------------------------------------
button:
Name "Submit":
<button
class="btn btn-primary"
/>
--------------------------------------------------
<body>
<div>
<div>
<form
data-testid="form"
>
<div
class="form-group"
>
<label
for="titleInput"
>
Title
</label>
<input
class="form-control"
data-testid="title"
id="titleInput"
name="title"
placeholder="Title"
type="text"
value="Lorem ipsum dolor sit amet, consectetur..."
/>
</div>
<button
class="btn btn-primary"
>
Submit
</button>
</form>
</div>
</div>
</body>
8 | fireEvent.change(input, { target: { value: "Lorem ipsum dolor sit amet, consectetur..." } })
9 |
> 10 | expect(screen.getByRole(/title/i)).toHaveTextContent('Lorem ipsum dolor sit amet, consectetur....')
| ^
11 | })
Aucun commentaire:
Enregistrer un commentaire