Testing previous and next button functionality in React fails
P粉936509635
2023-08-15 13:54:35
<p>My React code fails the test:
If I wrote it wrong, can you help me write it correctly?
I tried using screen.getByRole('button', {name: '>'}) to get the next button and screen.getByRole('button', {name: '<'}) to get the previous button, Even tried the test code mentioned below but the test kept failing. </p>
<pre class="brush:php;toolbar:false;">export default function App() {
return (
<div className="App">
<div>
{dogs
.map((value, key) => (
<div className="card-container" key={key}>
<div>
<img className="img" src={value.imgUrl} alt={value.title} />
</div>
<div className="card-footer">
{dogCurrPage !== 1 ? (
<button className="back-button" onClick={() => previous()}>
{"<"}
</button>
) : null}
<span className="card-title-text">{value.title}</span>
{dogCurrPage !== dogs.length - 1 ? (
<button className="next-button" onClick={() => next()}>
{">"}
</button>
) : null}{" "}
</div>
</div>
))}
</div>
</div>
);
}</pre>
<pre class="brush:php;toolbar:false;">describe("App", () => {
it("Properly handle the click of the previous button", () => {
render(<App />);
fireEvent.click(screen.getByText("<"));
});
it("Properly handle the click of the next button", () => {
render(<App />);
fireEvent.click(screen.getByText(">"));
});
});</pre>
Maybe try this code: