[英]How to test if React component is returning null or its children using React Testing Library?
I have a React component that returns its children
to be rendered by React if the prop isTrue
is truth-y.我有一个 React 组件,如果 prop
isTrue
是真值,则返回其children
级以由 React 呈现。 If its prop isTrue
is false-y, then the component returns null
, and React doesn't render anything.如果它的 prop
isTrue
为 false-y,则组件返回null
,并且 React 不会渲染任何内容。
I need to test it as a component, mount it, pass the prop, and test if it's children is getting rendered when the prop isTrue
is truth-y, or we are getting null
if isTrue
is false-y.我需要将它作为一个组件进行测试,安装它,传递道具,并测试当道具
isTrue
为真值时它的子项是否正在渲染,或者如果isTrue
为假值,我们将得到null
。
Here is my component:这是我的组件:
const RenderIf = ({ isTrue, children }) => {
if (isTrue) {
return children;
}
return null;
}
export default RenderIf
expect(container).toBeEmptyDOMElement()
import React from 'react'; import { render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; //... describe('TestHistory', () => { it('should render nothing if there are no history entries', () => { // ARRANGE // ACT const { container } = render( <TestHistory version={1} versionHistory={[]} datasetType={DatasetType.VALIDATION} />, ); // ASSERT expect(container).toBeEmptyDOMElement(); }); });
I'd think in this case it is probably ok to test the whole html.我认为在这种情况下,测试整个 html 可能是可以的。 react-testing-library wraps your content with a single div so you could something like that:
react-testing-library 用一个 div 包装你的内容,所以你可以这样:
const { container } = render(<MyComponent ifTrue={false}>Content</MyComponent>);
expect(container.innerHTML).toBe('<div></div>');
If you don't like this approach, you can still render a children with a test-id / text and query it to see if it's present.如果您不喜欢这种方法,您仍然可以使用 test-id / text 渲染一个孩子并查询它以查看它是否存在。
expect(container.innerHTML).toEqual('');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.