Ad

How To Mock Inline Refs In Jest & Enzyme

- 1 answer

I am new to jest and enzyme and I am trying to mock the refs of a component. I have seen many solutions but none seems to be related they way I created the refs.

my ref declaration :

<input type=email ref={ (input) => { this.email = input; } } />

and later when I am using ref in my component as :

this.email.focus();, i am getting error in test case : focus of undefined.

Test Case:

it('details', () => {
        wrapper = shallow(<Componentes  />);
        const instance = wrapper.instance();
        wrapper.email = {
            getRenderedComponent: jest.fn(() => ({
                focus: jest.fn
            }))
        };
        wrapper.find('.signin-button').simulate('click');
    });

Here I tries implementing one of the solution to my test case but that does not seem to be working. Any help on this would be greatly appreciated.

Thanks.

Ad

Answer

You'll want to add the mock to the instance of the component itself, like so:

it('details', () => {
    wrapper = shallow(<Componentes  />);
    const instance = wrapper.instance();
    instance.email = { focus: jest.fn() };
    wrapper.find('.signin-button').simulate('click');
});
Ad
source: stackoverflow.com
Ad