2

My component ->

export default()=>{
const [list, setList] = useState([])

 const handleAddToList = () => {
//makes an api call and sets the list state.
setList(response);
}
return (

<div>
  <Button onClick={hanldeAddToList}>add to list</Button>
{
list.map(row=><span>{row.name} </span>)
}
</div>
)

}

Problem =>

how to test this component using React testing library with mock list data, the problem is "list" is a state here and I cant test it using react testing library because it doesn't focus on the implementation and therefore I cant populate list state.

Manish
  • 67
  • 1
  • 8
  • What you really need to do is mock the call that fetches the data that populates your state. See the linked answer above. – Matt Morgan Nov 12 '21 at 12:15

1 Answers1

1

Like @matt-morgan said, you have to mock your api call. I would suggest using Mock Service Worker.

React Testing Library allows you to write tests against your UI in exactly the same was as a user does. Your tests will consist of clicking on buttons and filling in fields and clicking on links. If your component makes async calls for data, you have to mock those calls so that you UI has data to work with.

Steve -Cutter- Blades
  • 5,057
  • 2
  • 26
  • 40