How to test for tooltip title in jest and testing/library

There are multiple mistakes in your test.

  1. Passing component type instead of component instance to render
// this is wrong, passing component type
baseDom = render(cardComponent);

// this is right, passing component instance created with JSX
baseDom = render(<cardComponent />);
  1. Using mouseMove instead of mouseOver event

  2. Searching element by title and passing text instead of searching by text

// wrong, because, the prop on the Tooltip is called 'title'
// but it is actually text as 'getByTitle' looks for HTML
// title attribute
baseDom.getByTitle("Disconnected (Try again)");

// right, because you are actually looking for text not
// HTML title attribute (but wrong see (4))
baseDom.getByText("Disconnected (Try again)");
  1. Using sync method for Tooltip search instead of async
// wrong, because, Tooltip is added dynamically to the DOM
baseDom.getByText("Disconnected (Try again)");

// right
await baseDom.findByText("Disconnected (Try again)");

To sum up, with all mistakes fixed the test should look like this:

import React from "react";
import { render, fireEvent } from "@testing-library/react";
import App from "./App";

test("Show error title in tooltip", async () => {
  const baseDom = render(<cardComponent />);

  fireEvent.mouseOver(baseDom.getByTestId("connection-sign"));

  expect(
    await baseDom.findByText("Disconnected (Try again)")
  ).toBeInTheDocument();
});

Leave a Comment

tech