繁体   English   中英

测试 React 组件时如何设置子道具?

[英]How can I set child props when testing a React component?

我有这个组件

const InputWithLabel = ({
                          id,
                          value,
                          type = 'text',
                          onInputChange,
                          isFocused,
                          children,
                        }) => {...
return(<>
        <label htmlFor={id} className="label">
                {children}
        </label>
...
</>)}

我正在做测试:

describe('InputWithLabel',()=>{
    const inputWithLabelProps={
        id:"search",
        value:"React",
        isFocused:true,
        onInputChange:jest.fn,
        children:[]
    }
    test('check the existence of InputWithLabel',()=>{
        render(<InputWithLabel {...inputWithLabelProps}/>);
        screen.debug();// This to see the renders of the Element 
    });
})

我可以给孩子们带来什么价值:[] 做测试。 我尝试使用 object 数组,但没有用。 有任何想法吗?

在我的例子中,这是解决方案,这是组件的调用

<InputWithLabel
          id="search"
          value={searchTerm}
          isFocused
          onInputChange={onSearchInput}
      >
        <strong>Search:</strong>
      </InputWithLabel>

测试将是:

describe('InputWithLabel',()=>{
    const inputWithLabelProps={
        id:"search",
        value:"React",
        isFocused:true,
        onInputChange:jest.fn,
        children:<strong>Search:</strong>
    }
    test('check the existence of InputWithLabel',()=>{
        render(<InputWithLabel {...inputWithLabelProps}/>);
        screen.debug();
    });
})

请注意

<strong>Search:</strong>

是我的组件的孩子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM