how to write unit test for (EF) Element Framework in react 18?

Hi there,

I want to write unit tests for my react components in typescript. I am using (EF) Element Framework. React 18 and @testing-library/react. Basically, the default set up for create-react app.

I can only test functions. I cannot test any of the functionality of the EF components.

e.g. the debug methods show this for the toggle component

<body>

<ef-tooltip

ref="title-override"

/>

<div>

<ef-toggle />

</div>

</body>

  1. How can I select elements?

const { container } = render(<CurrencyPairToggle value={value} callback={setState} />)

const toggle = container.querySelector('ef-toggle')

debug()

This code works, but I do not think this is the right way of doing this.

Normal search variants do not work. E.g. queryByText, queryByRole

  1. Can I even trigger an event for the components. E.g fireEvent.click for a toggle?
  2. At least how can I test if the label or the checkedLabel are populated with the right value?
    1. E.g. expect(screen.getByRole("switch")).toHaveAttribute("label", "USD")
    2. Note: toggle uses the role ‘switch’


Many thanks for your help

Best Answer

  • Trying using the normal @testing-library/reac for elements like toggle.

    If your component is more complex you might try to use the container property from render and trigger the event by using a createEvent from @testing-library/react, Check the dummy code:

    import React from "react";

    import { render, fireEvent, createEvent, waitFor } from "@testing-library/react&quot;;

    import YourComponent from "./YourComponent";

    const testData = [

    {

    label: "Spot",

    value: "Spot",

    selected: true,

    },

    {

    label: "Tenor 2",

    value: "Tenor 2",

    },

    ];


    describe("<YourComponent />", () => {

    const setState = jest.fn();

    it("should match with snapshot", () => {

    render(<YourComponent data={testData} callback={setState} />);

    expect(render(<YourComponent data={testData} callback={setState} />)).toMatchSnapshot();

    });

    it("should call the callback fn", async () => {

    const callback = async (value: string) => {

    await waitFor(() => {

    expect(value).toEqual("Spot");

    });

    };

    const { container } = render(<YourComponent data={testData} callback={callback} />);

    const element = container.querySelector("ef-combo-box") as Element;

    const event = createEvent(

    "value-changed",

    element as Element,

    {

    detail: { value: "Spot" },

    },

    { EventType: "CustomEvent" },

    );


    fireEvent(element, event);

    fireEvent.keyUp(element as Element, { key: "Enter", code: "Enter" });

    });

    });

    Good luck!

Answers