mardi 1 décembre 2020

testing of REST is not working with react-testing-library and Mock Service Worker

I have the following component:

    export default function Recipes() {
      const [recipes, setRecipes] = useState({})
          const fetchAllRecipes = async () => {
            const response = await fetch('http://myurl/receipes')
            if (response.ok) {
              const jsonResponse = await response.json()
              setRecipes(jsonResponse)
            }
          }
        
          useEffect(() => {
            fetchAllRecipes()
          }, [])
return (
    <div>
      <ul>
        {Object.entries(recipes).map((element: any) => (
         <li>{element[1].id}</li>
 <li> {element[1].text}</li>
        ))}
      </ul>
    </div>

while my test file is the follwing:

const server = setupServer(
  rest.get('http://myurl/receipes', (_, res, ctx) => {
    // const bd = req.body
    ctx.status(200)
    return res(ctx.json({ allRecipes }))
  })
)
beforeAll(() => server.listen())
afterAll(() => server.close())


test('fetches and displays all receipes', async () => {
  render(<Recipes />)
  const listItems = await screen.findAllByRole('listitem')
  expect(listItems).toHaveLength(8)
  expect(listItems[0]).toHaveTextContent('burger')
  expect(listItems[1]).toHaveTextContent('fish')
  expect(listItems[2]).toHaveTextContent('pizza')
})

while my data coming from the server are like this:

{
    "0": {
        "id": "1",
        "text": "burger"
    },
    "1": {
        "id": "2",
        "text": "fish"
    },
    "2": {
        "id": "3",
        "text": "pizza"
    },
    "3": {
        "id": "4",
        "text": "lazagne"
    }
}

but the issue is that it's able to fetch the data but it cannot match them with the data comping from the server and it gives me this error:

● fetches and displays all receipes

    expect(received).toHaveLength(expected)

    Expected length: 8
    Received length: 2
    Received array:  [<li />, <li />]

So is there any case which you had the same?

Aucun commentaire:

Enregistrer un commentaire