Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React/JestJS/Enzyme: How to test for ref function?

I'm running unit tests using Jest and Enzyme for this very simple component render():

render() {
  return (<Input
    id='foo'
    ref={input => { this.refInput = input }}
  />)
}

it('should render Input', () => {
  wrapper = shallow(<Component />)
  expect(wrapper.find(Input)).toHaveLength(1)
})

I'm also using the coverage option of Jest and there I see, that the line

ref={input => { this.refInput = input }}

is not covered by my test. What do I have to do to get a full covered unit test for this sample component?

like image 653
user3142695 Avatar asked Jan 04 '18 04:01

user3142695


People also ask

How do you test for Jest and enzymes?

Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.

Can we use both Enzyme and React testing library?

A few days ago, React released version 18, which is not compatible with Enzyme. Furthermore, it probably is not achievable to use Enzyme with React 18. If you're still using Enzyme, it is time to look into alternatives. The most popular option besides Enzyme seems to be React Testing Library.


2 Answers

The ref is attached to an instance of the component hence you will have to use mount to get an instance of the component.

To test for the ref, add the following line

expect(wrapper.instance().refInput).toBeTruthy();

Final result:

render() {
  return (<Input
    id='foo'
    ref={input => { this.refInput = input }}
  />)
}

it('should render Input', () => {
  const wrapper = mount(<Component />);
  expect(wrapper.find(Input)).toHaveLength(1)
  expect(wrapper.instance().refInput).toBeTruthy();
})
like image 132
Yangshun Tay Avatar answered Oct 09 '22 18:10

Yangshun Tay


I solved the issue like this:

const ref = React.createRef();
const props = { register: jest.fn(params => ref), label: "label text", ...params };
let wrapper = mount(
    <ThemeProvider theme={theme}>
        <Input {...props} />
    </ThemeProvider>
);
expect(wrapper.find(Entity).getElement().ref).toBe(ref);

I have entity component inside input which receives ref function.

like image 5
vadimka Avatar answered Oct 09 '22 19:10

vadimka