簡體   English   中英

從 HTML 元素獲取 ref 值

[英]Get ref value from HTML element

如何從測試庫反應的 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
  })

也許這樣的事情就是你要找的:

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 示例,你可以在這里閱讀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM