使用 jest 和 react-testing-library 测试正确的 SVG 组件渲染

时间:2021-04-12 14:19:44

标签: reactjs svg jestjs react-testing-library

我在 React 组件中有一个有条件渲染的 svg。

<div className='avatar'>
      {gender === true ? <MaleAvatar /> : <FemaleAvatar />}
    </div>

MaleAvatar 和FemaleAvatar 是包含svgs 的组件。最初,我希望 MaleAvatar svg 呈现,然后如果性别的值更改为 false,FemaleAvatar svg 呈现 - 但男性头像应该首先呈现,这就是我想要测试的内容。

条件所在的组件是子组件的子组件,但我正在通过文本测试该组件中的元素并且测试工作正常,例如:

const personDetailsText = screen.getByText('Personal details')

我正在使用 jest 和 react-testing-library 进行测试,但是在父 div 上使用测试 ID 然后抓取第一个孩子不起作用,因为它无法识别测试 ID。所以如果我有:

<div data-testid='avatar' className='avatar'>
          {gender === true ? <MaleAvatar /> : <FemaleAvatar />}
        </div>

...然后下面的测试在 'const avatarSVG = screen.getByTestId('avatar')' 处失败:

test('gender avatar is male on initialisation', () => {
    const avatarSVG = screen.getByTestId('avatar')
    expect(avatarSVG).toBeInTheDocument()
    expect(() => screen.getByTestId('female-avatar').toThrow())
    expect(avatar.firstChild.nodeName).toBe('MaleAvatar')
  })

我正在使用 React 钩子,我读过我还需要在初始渲染后以某种方式补偿 React 渲染 SVG - 在 useEffect 完成后,但我无法找到如何使用 react-testing 来做到这一点 -库和钩子?

这也不起作用:

const avatarSVG = document.querySelector('MaleAvatar')

如何抓取 SVG 组件来检查渲染是否正确?

0 个答案:

没有答案
相关问题