[英]How to unit test a function that return JSX.element?
我有一個 function 接受一個參數並返回一個JSX.Element
//title.tsx
export const getTitle = (pageTitle: string) => {
return <title> {pageTitle} </title>;
}
這就是我測試它的方式:
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);
});
});
測試失敗並顯示以下 output:
Expected value: "abc"
Received object: <React.Fragment><title>abc</title></React.Fragment>
根據一些研究,我在谷歌上找到了一個解決方案,它假設 function 是 class 組件的一部分。 該解決方案要求wrapper
在傳遞基於類的組件ControlledForm
時由shallow
返回。 這不適用於我的情況。
如何從
JSX.element
返回的 JSX.element 中提取文本值以與一些預期文本進行比較?
還是有另一種方法來測試這種情況?
Go換道具還是用淺的。 我不知道哪個是紅色葯丸。
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);
要么
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.