0

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
  })
Harry
  • 39
  • 4
  • 1
    Does this answer your question? [React/JestJS/Enzyme: How to test for ref function?](https://stackoverflow.com/questions/48088489/react-jestjs-enzyme-how-to-test-for-ref-function) – Jax-p Nov 08 '21 at 13:32
  • This solution is what I want but since I'm not using Enzyme, it wont work :l Trying to get the ref of this guy `const container = screen.getByTestId('container')` it is an HTMLElement – Harry Nov 08 '21 at 13:40
  • Why do you need to get the `ref` from that component? Can you not test the behaviour where that `ref` is used instead? – juliomalves Nov 08 '21 at 23:30

1 Answers1

0

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

  • I want to get the reference after render the component, so I wont have a const with createRef to get its value. My component doesn't receive ref as props the ref is on its wrapper. So getting the ref from this guy `const container = screen.getByTestId('container')` that is a HTMLElement would be my goal. – Harry Nov 08 '21 at 13:50