Skip to content Skip to sidebar Skip to footer

Reactjs: How To Test For A Ref?

This is a function used in a react component. As you can see I'm using ref to get the focus on a specific input element of another component. myFunction (param) { this.refInput &

Solution 1:

Try doing something like this:

it('myFunction() should call focus()', () => {
  // SETUP
  wrapper = mount(<Example />)
  // EXECUTE
  wrapper.instance().myFunction('anything')
  // VERIFYconst elem = wrapper.find('#foo'); 
  const focusedElement = document.activeElement;
  expect(elem.matchesElement(focusedElement)).to.equal(true);
})

Points to note:

  1. Use Mount rather than Shallow, as @Marouen Mhiri commented, shallow rendering can't hold a ref

  2. You don't need to pass ref as props (in fact it's wrong)

  3. Where I have wrapper.find('#foo'), replace foo by class/id of the DOM element in Input

Post a Comment for "Reactjs: How To Test For A Ref?"