简体   繁体   中英

Get ref value from HTML element

How can I get the ref prop from a HTML element on testing library react? I have this so far:

  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
  })

Maybe something like that is what you're looking for:

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');
});

It comes from the react example of jest, you can read it about here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM