【问题标题】:Testing library with children component使用子组件测试库
【发布时间】:2023-01-11 05:11:21
【问题描述】:

我有一个具有子组件的父组件“Parent”,我想测试这些子组件是否使用测试库呈现。如何才能做到这一点?

export function Parent({
  children,
  id,
  ...props
}: React.HTMLAttributes<HTMLDivElement> & HtmlFieldProps) {
 
  return (
    <div id={id} {...props} className={props.className}>
      <div>{children}</div>
    </div>
  );
}

【问题讨论】:

  • 你给它一个孩子然后检查它是否被渲染。例如:渲染它包装一些你可以轻松选择的东西(例如&lt;span data-testid="child" /&gt;)然后断言它的存在?
  • 没有看到孩子们的样子很难说。他们有角色或文本吗?在许多情况下,这些比测试 ID 更受欢迎。

标签: reactjs react-testing-library


【解决方案1】:

如果您正在对组件进行单元测试,并且只想检查它是否可以渲染子组件,那么它非常简单:

const testProps = {
  ...props,
  children: 'test child',
};

it('renders children', () => {
  render(<Parent {...testProps} />);
  const child = screen.getByText('test child');
  expect(child).toBeInTheDocument();
});

如果您正在编写集成测试,那么这将取决于您如何实现/使用该组件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 2021-07-26
    • 2019-09-24
    • 2020-11-05
    相关资源
    最近更新 更多