four-eyes
four-eyes

Reputation: 12394

Call function passed as prop in Enzym

My Component looks like this

const FooBar = ({
    onClose,
}) => {
    return (
        <div
            className='foo'>
            <Icon
                name='close'

                onClick={onClose} />
        </div>
    )
}

My test looks the following

const mockFn = jest.fn();
const title = 'Title';

it('calls the onClose function', () => {
    const component = mount(
        <FooBar
            title={title}

            onClose={mockFn}
        />
    );

    component.instance().onClose();
    expect(mockFn).toBeCalled();
    component.unmount();
});

That returns

TypeError: Cannot read property 'onClose' of null

How do I call the onClose function?

Upvotes: 0

Views: 46

Answers (1)

Herman Starikov
Herman Starikov

Reputation: 2756

Try

component.find(Icon).first().props().onClick();

Also, take a look at react-testing-library it makes this kind of testing easier.

Upvotes: 1

Related Questions