brff19
brff19

Reputation: 834

Testing nested JSX with React Testing Library

I am trying to run a test where I can validate that a userList prop is being rendered. As of now when I run screen.debug(), it shows all the HTML except the HTML inside the nested brackets in the body of the code within the return area. Below is my test and the component (UserList) that is using it.

describe("The App component", () => {
  it("renders a UserList component",  async () => {
    render(<UsersList userList={[{id: 0, title: "asdf"}, {id: 1, title: "zxcv"}]}/>);
    const ul = await screen.getByRole("list");
    expect(ul.childElementCount > 0).toBe(true);
  })
})

import * as React from "react";

const UsersList = (props: any) => {
  return (
    <>
      <ul>
        {
          props.usersList ? props.usersList.map((user: any) => {
              return (
                <li key={user.id}>{user.title}</li>
              )
            })
            : null
        }
      </ul>
    </>
  )
}

export default UsersList

With the following error:

    ✕ renders a UserList component (9 ms)

  ● The App component › renders a UserList component

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      28 |     render(<UsersList userList={[{id: 0, title: "asdf"}, {id: 1, title: "zxcv"}]}/>);
      29 |     const ul = await screen.getByRole("list");
    > 30 |     expect(ul.childElementCount > 0).toBe(true);
         |                                      ^
      31 |   })
      32 | })

      at Object.<anonymous> (src/tests/App.test.tsx:30:38)

Upvotes: 0

Views: 1535

Answers (1)

Irvin Sandoval
Irvin Sandoval

Reputation: 751

It looks like the actual prop that UsersList component expects is usersList so you have to pass the right prop in your test:

describe("The App component", () => {
    it("renders a UserList component",  async () => {
        render(<UsersList usersList={[{id: 0, title: "asdf"}, {id: 1, title: "zxcv"}]}/>);
        const ul = await screen.getByRole("list");
        expect(ul.childElementCount > 0).toBe(true);
    })
})

Upvotes: 2

Related Questions