I want to test that the tooltip title is equal to a specific text or not. This is my antd tooltip I want to write a test for that:
<Tooltip
title={
this.props.connection ? "Connected" : "Disconnected (Try again)"
}>
<Badge status="default" data-testid="connection-sign" />
</Tooltip>
and this is my test in jest:
test("Show error title in tooltip", async () => {
baseDom = render(cardComponent);
fireEvent.mouseMove(await baseDom.findByTestId("connection-sign")); //To hover element and show tooltip
expect(
baseDom.getByTitle(
"Disconnected (Try again)"
)
).toBeInTheDocument();
});
but this test failed and unable to find an element with this title. How can I test that my tooltip contain "Disconnected (Try again)"?
You can use testing-library/jest-dom custom matchers. The @testing-library/jest-dom library provides a set of custom jest matchers that you can use to extend jest. These will make your tests more declarative, clear to read and to maintain. Save this answer.
You will use Jest to write and run unit tests, and you will implement React Testing Library as a helper DOM (Document Object Model) library to handle interacting with components.
To find elements by className in React testing library: Render a component and destructure the container object from the result. Use the getElementsByClassName() method on the container to find elements by class name.
There are multiple mistakes in your test.
render
baseDom = render(cardComponent); // this is wrong, passing component type
baseDom = render(<cardComponent />); // this is right, passing component instance created with JSX
Using mouseMove
instead of mouseOver
event
Searching element by title and passing text instead of searching by text
baseDom.getByTitle("Disconnected (Try again)"); // wrong, because, the prop on the Tooltip is called 'title' but it is actually text as 'getByTitle' looks for HTML title attribute
baseDom.getByText("Disconnected (Try again)"); // right, because you are actually looking for text not HTML title attribute (but wrong see (4))
baseDom.getByText("Disconnected (Try again)"); // wrong, because, Tooltip is added dynamically to the DOM
await baseDom.findByText("Disconnected (Try again)"); // right
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With