我有一个包裹所有屏幕的组件:
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);
});
});
});
答案 0 :(得分:3)
您可以创建一些测试子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);
});
});
});