[英]React / React Native + Enzyme: How to test if a component renders it's children?
I have a component with which I wrap all my screens: 我有一个组件用于包装我的所有屏幕:
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;
I'm currently writing it's unit tests. 我正在编写它的单元测试。 I would like to test if this component renders its children. 我想测试这个组件是否呈现它的子代。 How can I do this? 我怎样才能做到这一点?
Here is the code that I've written (but even though the component works, the test does not pass): 这是我编写的代码(但即使组件有效,测试也没有通过):
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);
});
});
});
How could I write a test that checks if the component renders it's children? 我怎么能写一个测试来检查组件是否呈现它的孩子?
EDIT: Through the answer from eramit I implemented this check like this: 编辑:通过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);
});
});
});
You could create some test child div and check. 您可以创建一些测试子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);
});
});
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.