F
F
Fannasankh2019-11-18 10:32:24
Software testing
Fannasankh, 2019-11-18 10:32:24

How to do click testing in React?

There is a React application which, roughly speaking, consists of a main statefull component and nested stateless components. Nested components have click handling that calls props-passed methods from the main component. How can I test a click and that after the click a new result is rendered in a certain field?
Just rendering the result at the start of the application I did, it works.
But clicks cannot be emulated.
I do something like this
const component = mount();
const buttons = component.find(Button);
buttons.at(0).simulate("click");
component.update();
const text = component.find(TextComponent);
expect(text.text()).toEqual("-");
In theory, there is a "-" during initialization, and when clicked, it should change, but nothing changes

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
camelCaseVlad, 2019-11-18
@Fannasankh

Here's how you can test a simple button:

test('button executes Onclick ', () => {
    const wrapper = mount(<ButtonComponent onClick={jest.fn()} />);
    wrapper.find('button').simulate('click');
    expect(wrapper.props().onClick).toBeCalled();
  });

Here is an option on how to test a function that was passed as a prop:
test('MyComponent', () => {
    const myFn = jest.fn();
    const props = { myFn, ...otherProps }
    const wrapper = mount(
        <MyComponent {props}/>
    );
       wrapper.find('button').simulate('click');
      wrapper.update();
      expect(wrapper.props().myFn).toBeCalled();
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question