【问题标题】:Test enclosing component inside a React functional component using Jest/Enzyme使用 Jest/Enzyme 在 React 功能组件中测试封闭组件
【发布时间】:2020-11-02 19:51:10
【问题描述】:

我有一个名为Post 的组件,其中有一个名为Div 的封闭组件。运行测试覆盖率时,Div 部分似乎没有被覆盖。然而,Post 被覆盖了。我怎样才能覆盖Div 部分。有人可以帮忙吗?

const Post = ({id, title}) => (
 <Div>
  <Title name={title} />
 </Div>
);

这是我的测试用例

describe('Post component', () => {
  const props = {
    id: '1',
    title: 'Test',
  };
  it('renders post', () => {
    const component = shallow(<Post {...props} />);
    expect(component).toMatchSnapshot();
  });
});

【问题讨论】:

  • DivTitle 是什么?需要浅渲染吗?
  • 这些是styled 组件,只是添加了填充和边距。

标签: javascript reactjs ecmascript-6 jestjs


【解决方案1】:

根据您的评论,您似乎拥有名为 DivTitle 的样式化组件。如果你有它的函数的导出语句,你可以在这里通过发送它们的道具来调用它们,比如你如何对组件进行浅层测试。 如果你有类似的东西

export const Div = () => {}

export const Title = () => {}

export const Post = () => {}

你的测试用例应该是

describe('Post component', () => {
  const props = {
    id: '1',
    title: 'Test',
  };
  it('renders post', () => {
    const component = shallow(<Post {...props} />);
    expect(component).toMatchSnapshot();
  });

 it('renders Div', () => {
    const component = shallow(<Div {...props} />);
    expect(component).toMatchSnapshot();
  });

 it('renders Title', () => {
    const component = shallow(<Title {...props} />);
    expect(component).toMatchSnapshot();
  });
});

这样,您将覆盖整个功能组件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2017-02-12
    • 2018-08-20
    • 2020-04-08
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多