简体   繁体   English

如何对返回 JSX.element 的 function 进行单元测试?

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

I have a function that accepts a parameter and returns a JSX.Element我有一个 function 接受一个参数并返回一个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:测试失败并显示以下 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.根据一些研究,我在谷歌上找到了一个解决方案,它假设 function 是 class 组件的一部分。 The solution requires wrapper to be an returned by shallow while passing the class-based component ControlledForm ) .该解决方案要求wrapper 在传递基于类的组件ControlledForm时由shallow返回 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?如何从JSX.element返回的 JSX.element 中提取文本值以与一些预期文本进行比较?

Or is there another way to test such cases?还是有另一种方法来测试这种情况?

Go for the props or use another shallow. Go换道具还是用浅的。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM