I
I
ihoryan2018-07-17 12:28:00
React
ihoryan, 2018-07-17 12:28:00

How to test button component in React?

Hello!
There is a Button component:

const Button = (props) => {
    return (
        <button
            disabled={props.disabled}
            type="button"
            onClick={props.action}
        >
            {props.children}
        </button>
    );
};

Wrote this test:
import React from 'react';
import { shallow, mount } from 'enzyme';

import Button from './Button';

describe('<Button />', () => {
    let wrapper, actionMock;

    beforeEach(() => {
        actionMock = jest.fn();
        wrapper = shallow(<Button action={actionMock}>Cancel</Button>);
    });

    it('should render correctly', () => {
        expect(wrapper.find('button')).toHaveLength(1);
        expect(wrapper.text()).toEqual('Cancel');
    });

    it('action function should be invoked after click', () => {
        wrapper.find('button').simulate('click');
        expect(actionMock).toHaveBeenCalled();
    });

    it('should not react on click if disabled prop was passed ', () => {
        wrapper = shallow(<Button action={actionMock} disabled={true}>Cancel</Button>);

        expect(wrapper.props().disabled).toEqual(true);

        wrapper.find('button').simulate('click');
        expect(actionMock).not.toHaveBeenCalled();
    });
});

But the last test fails, since the button does not receive the disabled attribute, so when a click is simulated, the handler is called. I tried to pass the disabled prop in different ways both as true and as disabled. Used shallow and mount methods. Nothing works.
And secondly, if you add console.log(props) in the Button component itself, and pass some arbitrary props in tests, for example test="test", then it is not displayed in the console, but only action and disabled, although the latter is not works as it should.
PS The first question is removed - when using mount the test passed, the second one is still relevant.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-07-17
@maxfarseer

In a comment to the question, I answered the log about the console, and about the click, it seems that this is a bug in enzyme:
1) https://github.com/airbnb/enzyme/issues/749
2) https://github.com/airbnb/ enzyme/issues/386
therefore, you can use in the test just checking that the button has a disabled attribute if you passed it to props (relevant info here - https://github.com/airbnb/enzyme/issues/336 )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question