Home > Software design >  TestingLibraryElementError: Unable to find an accessible element with the role "link" in t
TestingLibraryElementError: Unable to find an accessible element with the role "link" in t

Time:11-18

In the Next.js application, I am getting the error

TestingLibraryElementError: Unable to find an accessible element with the role "link" 

while performing below assertion -

expect(screen.getAllByRole("link").length).toEqual(1);

for the anchor tag that is wrapped in Link Component of next.js

 <Link href={`/article/${Id}`} >
                    <a
                      title={Title}
                      onClick={() => {
                        ///
                      }}
                    >
                      {Title}
                    </a>
  </Link>
 

CodePudding user response:

Wrap the link component around routes and return in the render method

describe('test', () => {
    it("should link", () => {
        render(
            <MemoryRouter>
                <Routes>
                    <Route path="/" element={<Your_Component_with_link/>}/>
                </Routes>
            </MemoryRouter>,
        );
        expect(screen.getAllByRole("link").length).toEqual(1);

    });
});

CodePudding user response:

Generally we have the assumption that the default role for is "link" but that is not true.

Here in Next.js application we are passing the href to Link and not to so is not getting the href directly at leaset it is not there when we try to see screen log using screen.debug()

Title

So the only solution I found was to provide the role manually in Next.js App

<Link href={`/article/${Id}`} >
                    <a
                      role="link"
                      title={Title}
                      onClick={() => {
                        ///
                      }}
                    >
                      {Title}
                    </a>
  </Link>
  • Related