最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React Testing Library: Unable to Find Element by data-testid During Test - Stack Overflow

programmeradmin1浏览0评论

I am encountering an error when testing a React component using React Testing Library. The test fails to find an element with data-testid="resCard" even though I believe it should be rendered.

Error details

● Should render the body component with search

TestingLibraryElementError: Unable to find an element by: [data-testid="resCard"]                                                
                                                                                                                                 
Ignored nodes: comments, script, style                                                                                           
<body>                                                                                                                           
  <div>
    <div
      class="body"
    >
      <div
        class="filter flex items-center"
      >
        <input
          class="border border-solid border-black px-3 py-1 ml-5"
          data-testid="searchInput"
          type="text"
          value="burger"
        />
        <button
          class="search-container  px-4 py-2 bg-green-100 ml-3 rounded-lg"
        >
          Search
        </button>
        <div
          class="search m-3 p-3 items-center"
        >
          <button
            class="px-5 py-4 bg-grey-500 rounded-lg"
          >
            Top Rated Restuarant
          </button>
        </div>
      </div>
      <div
        class="flex flex-wrap"
      />
    </div>
  </div>
</body>

  34 | fireEvent.click(searchBtn);
  35 |
> 36 | const cardsAfterSearch = screen.getAllByTestId("resCard");
     |                                 ^
  37 |
  38 | expect(cardsAfterSearch.length).toBe(1);
  39 | });

  at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
  at node_modules/@testing-library/dom/dist/query-helpers.js:76:38
  at node_modules/@testing-library/dom/dist/query-helpers.js:109:15
  at Object.getAllByTestId (src/components/__test__/Search.test.js:36:33)

Search.test.js

import Body from "../Body";
import { fireEvent, render , screen} from "@testing-library/react";
import MOCK_DATA from "../mock/bodyMock.json";
import { act } from '@testing-library/react';
import { BrowserRouter } from "react-router-dom";
import "@testing-library/jest-dom";
//Global is a global object wherever the body component is rendered, creating mock fetch function.

global.fetch = jest.fn(() =>{
    return Promise.resolve({
        json: () => {
            return Promise.resolve(MOCK_DATA);
            //Here the data that return.
        }
    })
});

test("Should render the body component with search", async() => {

//Act is basically a promise
    await act(async () => 
        render(<BrowserRouter><Body />
        </BrowserRouter>
        )
    );


const searchBtn = screen.getByRole("button", { name: "Search" });

const searchInput = screen.getByTestId("searchInput");

fireEvent.change(searchInput, { target: { value: "burger" } });

fireEvent.click(searchBtn);

const cardsAfterSearch = screen.getAllByTestId("resCard");

expect(cardsAfterSearch.length).toBe(1);
});

RestaurantCard.js

  import { CDN_URL } from "../utils/constants";

const styleCard = {
    backgroundColor: "#f0f0f0"
 };

const RestuarantCard =(props) =>{
    const {resData} = props;
    console.log(resData);
    const {cloudinaryImageId,name,cuisines,avgRating,costForTwo} = resData?.info;
    
    return(
       <div data-testid = "resCard" className="m-4 p-4 w-[300px] rounded-lg" style={styleCard}>
          <img className = "rounded-lg w-full h-[180px] object-cover" src ={CDN_URL + cloudinaryImageId}/>
          <h3 className="font-bold text-lg truncate">{name}</h3> 
          <h4 className="whitespace-normal overflow-hidden text-ellipsis">{cuisines.join(",")}</h4>
          <h4> {avgRating}</h4>
          <h4> {costForTwo}</h4>
       </div>
    );
 };

 export const withPromotedLabel = (RestuarantCard) => {
   return (props) => {
      return (
         <div>
            <label>Promoted</label>
            <RestuarantCard {...props}/>
         </div>
      )
   }
 }
 export default RestuarantCard;

Inside RestaurantCard.js I have provide data-testid = "resCard", but still the issue persists.

1.How can I resolve this error,please help.

发布评论

评论列表(0)

  1. 暂无评论