【问题标题】:Get ref value from HTML element从 HTML 元素中获取 ref 值
【发布时间】:2021-11-08 13:25:26
【问题描述】:

如何从测试库反应的 HTML 元素中获取 ref 属性?到目前为止我有这个:

  it('element container ref should be null if prop noSwipe is passed', () => {
    const onCloseMock = jest.fn()
    render(<Wrapper onClose={onCloseMock} noSwipe />)
    const container = screen.getByTestId('container')
    expect(container.ref).toBeNull() // Want to implement this line
  })

【问题讨论】:

  • 这个解决方案是我想要的,但是因为我没有使用 Enzyme,所以它不会工作:l 试图获得这个人的 ref const container = screen.getByTestId('container') 它是一个 HTMLElement
  • 为什么需要从该组件中获取ref?你能不测试使用 ref 的行为吗?

标签: javascript reactjs jestjs testing-library


【解决方案1】:

也许你正在寻找类似的东西:

import React, {createRef} from 'react';

import * as TestUtils from 'react-dom/test-utils';
import CheckboxWithLabel from '../CheckboxWithLabel';

it('CheckboxWithLabel changes the text after click', () => {
  const checkboxLabelRef = createRef();
  const checkboxInputRef = createRef();
  // Render a checkbox with label in the document
  TestUtils.renderIntoDocument(
    <CheckboxWithLabel
      labelRef={checkboxLabelRef}
      inputRef={checkboxInputRef}
      labelOn="On"
      labelOff="Off"
    />,
  );

  const labelNode = checkboxLabelRef.current;
  const inputNode = checkboxInputRef.current;

  // Verify that it's Off by default
  expect(labelNode.textContent).toEqual('Off');

  // Simulate a click and verify that it is now On
  TestUtils.Simulate.change(inputNode);
  expect(labelNode.textContent).toEqual('On');
});

来自jest的react例子,大家可以阅读一下here

【讨论】:

  • 我想在渲染组件后获取引用,所以我不会有一个带有 createRef 的 const 来获取它的值。我的组件没有收到 ref 作为 ref 在其包装器上的道具。所以从这个家伙const container = screen.getByTestId('container') 那里得到一个 HTMLElement 的 ref 将是我的目标。
猜你喜欢
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 2021-05-29
  • 2020-06-30
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多