Testing previous and next button functionality in React fails
P粉936509635
P粉936509635 2023-08-15 13:54:35
0
1
456
<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>
P粉936509635
P粉936509635

reply all(1)
P粉648469285

Maybe try this code:

describe("App", () => {
  it("正确渲染应用程序", async() => {
    render( < App / > );

    // 根据您的UI组件添加更具体的断言
    expect(screen.getByText("Fetch Api, display 1 card, add comments and likes to those comments")).toBeInTheDocument();
  });

  it("正确处理上一个按钮的点击", async() => {
    render( < App / > );

    fireEvent.click(screen.getByRole("button", {
      name: "<"
    }));
    // 添加断言以检查点击上一个按钮后的行为
  });

  it("正确处理下一个按钮的点击", async() => {
    render( < App / > );

    fireEvent.click(screen.getByRole("button", {
      name: ">"
    }));
    // 添加断言以检查点击下一个按钮后的行为
  });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template