gpt4 book ai didi

reactjs - React/React Native + enzyme : How to test if a component renders it's children?

转载 作者:行者123 更新时间:2023-12-03 14:13:05 25 4
gpt4 key购买 nike

我有一个组件可以用来包裹我的所有屏幕:

import React from "react";
import { SafeAreaView } from "react-native";
import { PropTypes } from "prop-types";

import styles from "./styles";

const SafeContainer = ({ children }) => {
return <SafeAreaView style={styles.container}>{children}</SafeAreaView>;
};

SafeContainer.propTypes = {
children: PropTypes.any
};

export default SafeContainer;

我目前正在编写它的单元测试。我想测试这个组件是否渲染它的子组件。我怎样才能做到这一点?

这是我编写的代码(但即使组件工作,测试也没有通过):

import React from "react";
import { shallow } from "enzyme";
import SafeContainer from "./SafeContainer";

describe("SafeContainer", () => {
describe("rendering", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<SafeContainer />);
});

it("should render a <SafeAreaView />", () => {
expect(wrapper.find("SafeAreaView")).toHaveLength(1);
});

it("should render its children", () => {
expect(wrapper.children()).toEqual(wrapper.props().children);
});
});
});

我如何编写一个测试来检查组件是否呈现其子组件?

编辑:通过 eramit 的回答我像这样实现了这个检查:

describe("SafeContainer", () => {
describe("rendering", () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(
<SafeContainer>
<View className="Test" />
</SafeContainer>
);
});

it("should render a <SafeAreaView />", () => {
expect(wrapper.find("SafeAreaView")).toHaveLength(1);
});

it("should render its children", () => {
expect(wrapper.find(".Test")).toHaveLength(1);
});
});
});

最佳答案

您可以创建一些测试子 div 并检查。

describe("SafeContainer", () => {
describe("rendering", () => {
let wrapper;
beforeEach(() => {
const TestComponent = <SafeContainer><div className="Test"/></SafeContainer>
wrapper = mount(<TestComponent />);
});

it("should render a <SafeAreaView />", () => {
expect(wrapper.find("SafeAreaView")).toHaveLength(1);
});

it("should render its children", () => {
expect(wrapper.find(".Test")).toHaveLength(1);
});
});

});

关于reactjs - React/React Native + enzyme : How to test if a component renders it's children?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51233545/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com