English 中文(简体)
Bugs while testing react for asynchronous tasks, Unable to find an element by: [data-testid="reload-button"]
原标题:

** Unable to find an element by: [data-testid="reload-button"]**

Facing issues when testing a create-react-app using RTL.

I ve a simple react project wherein I m making a call over the internet to display a list of users. While writing a testcase for the same, I m trying to mock a fetch call and provide dummy data as well so that my app doesn t increase load on the server.

But I m facing issues in this.

I get an error saying:

`Unable to find an element by: [data-testid="reload-button"]

Ignored nodes: comments, script, style
<body>
  <div />
</body>

  15 |     render(<Body  />)
  16 |
> 17 |     await waitFor(()=>expect(screen.getByTestId("reload-button")))
     |                  ^
  18 |     const usersArray = screen.getAllByTestId("users-list")
  19 |     expect(usersArray.length).toBe(5)
  20 | })

  at waitForWrapper (node_modules/@testing-library/react/node_modules/@testing-library/dom/dist/wait-for.js:166:27)
  at Object.<anonymous> (src/components/__tests___/Body.test.js:17:18)`

My code is as follows:

The component where an api call is made, using which the state is changed and data is passed on to the as props

//Body.js

const Body = () => {
    const [ users, setUsers ] = useState([])
    const  [ reloadUsers , setReloadUsers] = useState(false)
    useEffect(() =>{
        fetchUsers()
    },[reloadUsers])

    const fetchUsers = async () => {
        const data = await fetch(`https://randomuser.me/api/?results=5`) 
        const jsonData = await data.json()
        setUsers(jsonData?.results)
    }
    if(!users)return null

    return users.length===0 ? <p>Loading...</p> :  (
        <div>
            <button 
               data-testid= reload-button  
               onClick={()=> setReloadUsers(prev => !prev) } >
               Load different users
            </button>
            <UserList users={users}  />
        </div>
      )
}

The component receiveing the data as props and then mapping over it to display the data

//UserList.js

const UserList = ({users}) => {
    const displayList = users.map(user=>(
        <li data-testid="users-list"  
            style={{ display  :  flex  ,  alignItems  :  center  ,  margin  :  20px }}  
            key={user?.login?.uuid} 
        >
            <img  
              style={{ borderRadius : 30px  ,  marginRight  :  20px }} 
              src={user?.picture?.thumbnail} alt= thumbnail   />
            <span>{user?.name?.first} {user?.name?.last} </span>
        </li>
    ))
  return (
    <div>
        <h5>UserList</h5>
        <ul style={{  listStyleType  :  none  }} >
            {displayList}
        </ul>
    </div>
  )
}


My test file is as follows where I m testing if the mock data is getting populated

//Body.test.js

import { render, screen, waitFor } from "@testing-library/react"
import Body from "../Body"
import { usersList } from "../utils/constants";

test( user list should appear on screen , async ()=>{

    global.fetch = jest.fn(()=>{
        return Promise.resolve({
            json : () => {
                return Promise.resolve(usersList)
            }
        })
    })

    render(<Body  />)

    await waitFor(()=>expect(screen.getByTestId("reload-button")))
    const usersArray = screen.getAllByTestId("users-list")
    expect(usersArray.length).toBe(5)
})

What is the mistake that I m doing?

问题回答

暂无回答




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签