Answer the question
In order to leave comments, you need to log in
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>
);
};
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();
});
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question