How to unit test a function that return JSX.element?

Viewed 3639

I have a function that accepts a parameter and returns a JSX.Element

//title.tsx
export const getTitle = (pageTitle: string) => {
    return <title> {pageTitle} </title>;
}

This is how I'm testing it:

describe('Title component', () => {    
    test("Title component is rendered", () => {
        const wrapper = getTitle('abc');
        const expectedText = `abc`;
        const actualText = wrapper; //wrapper.text() does not exists;
        expect(actualText).toContain(expectedText);
    });
});

The test fails with the following output:

Expected value: "abc"
Received object: <React.Fragment><title>abc</title></React.Fragment>

As per some research, I found a solution on Google, which assumes that the function is part of a class component. The solution requires wrapper to be an returned by shallow while passing the class-based component ControlledForm). This does not apply to my case.

How to extract the text value out of JSX.element returned by the function to compare with some expected text?

Or is there another way to test such cases?

1 Answers

Go for the props or use another shallow. I don't know which one is the red pill.

const titleName = "titleName";
const wrapper = shallow(getTitle(titleName));
const titleElement = wrapper.getElement("title");
titleElement.props.children[1] // "titleName" as [0] and [2] are " "
const containsTitle = titleElement.props.children.includes(titleName);
expect(containsTitle).toBe(true);

or

const titleName = "titleName";
const wrapper = shallow(getTitle(titleName));
const titleElement = wrapper.getElement("title");
const secondWrapper = shallow(titleElement);
secondWrapper.text() // "titleName"
const containsTitle = secondWrapper.contains(titleName);
expect(containsTitle).toBe(true);
Related