How to define container size for react-testing-library?

Bru*_*iro 10 javascript jsdom reactjs jestjs react-testing-library

I have looked into similar questions (like this one), but the proposed solutions didn't work for me when using react-testing-library.

I have a component that can receive multiple children. This component will then calculate its own size and its children size, to check how many children it will be able to render. It works fine when I use it in my application.

My problem is that, when rendering this component with react-testing-library, the container of the component is rendered with a 0 height and width; so my component will understand that there are no available space to render any child.

I tried to define a custom container inside the tests; tried to force some styling to set width and height; but none of that worked.

Is there a way to "fix" that?

Component (omitted some of the code for the purposes of this question):

const ParentComponent = (props) => {
  const [visibleChildren, setVisibleChildren] = useState(0)
  const myself = useRef(null)

  useEffect(() => {
    const componentWidth = myself.current.offsetWidth;
    const childrenWidth = myself.current.children.reduce(
      // Returns the total children width
    )

    // Returns the number of children I can display
    const childrenAmount = calculateSpace()
    setVisibleChildren(childrenAmount)
  }, [myself])

  // Slice the array of children to display only the right amount
  slicedChildren = props.children.slice(0, visibleChildren)

  return (
    <div ref={myself}>
      {slicedChildren}
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

Use:

<ParentComponent>
  <Child />
  <Child />
  <Child />
</ParentComponent>
Run Code Online (Sandbox Code Playgroud)

Test:

import React from 'react'
import {render} from '@testing-library/react'
import ParentComponent from '../ParentComponent'

test('Render component', () => {
  const { getAllByRole } = render(
    <ParentComponent>
      <Child />
      <Child />
      <Child />
    </ParentComponent>
  )

  expect(getAllByRole("Child").length).toEqual(3)
})
Run Code Online (Sandbox Code Playgroud)

Updated:

Added this codesandbox example.

sky*_*yer 10

我们可以直接模拟该属性HTMLElement.prototype

Object.defineProperties(window.HTMLElement.prototype, {
  offsetWidth: {
    get: function() { return this.tagName === 'SPAN' ? 100: 500}
  }
});
Run Code Online (Sandbox Code Playgroud)

感谢https://github.com/jsdom/jsdom/issues/135#issuecomment-68191941

看看 issue,它有 looooong 故事(自 2011 年以来!)但仍然打开

说实话,我看到嘲笑offsetWidth测试逻辑更可靠。我不希望测试环境一直计算真实的样式(如偏移大小)。

  • 嗨布鲁诺,拜托,我面临着类似的问题。您在测试代码中的具体位置应用了上述代码片段?谢谢。 (2认同)