mangusbrother mangusbrother - 26 days ago 30
React JSX Question

Wait for condition in Enzyme and Jest (eventual consistency, assert with timeout)

I have a simple test:

import React from 'react';
import GenericButton from 'components/buttons/GenericButton';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';

describe('Generic Button', () => {
test('Button action called when clicked', () => {
var clicked = false;
const component = shallow(
<GenericButton action={() => {
clicked = true;
}}
id="testComponent"/>
);

component.find('testComponent').first().simulate('click');
expect(clicked).toBeTruthy();
});
});


However this will fail as the action is done eventually,

If i set the assertion to happen eventually (using setTimeout for example) it will work

however it would be better if i do something of the following before the assert (found this on examples using jasmine)

waitsFor(() => {
return clicked;
}, "the value to change", 1000);


What is the equivalent call for enzyme/jest?




Edit: Content of component

render() {
return <Button id={this.props.id}
key={this.props.id}
onClick={() => this.props.action()}
bsStyle={this.props.style}>
{this.props.text}
</Button>;
}


(Button is a 3rd party library component)

Answer

To test if a click handler was added correctly pass a spy into your comment, simulate the click and check that the spy was called. Doing this there is no need to use waitsFor.

import React from 'react';
import GenericButton from 'components/buttons/GenericButton';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';

describe('Generic Button', () = > {
  test('Button action called when clicked', () = > {
    const action = jest.fn();
    const component = shallow(
      <GenericButton action={action}
            id="testComponent"/>
    );
    component.find('Button').first().simulate('click');
    expect(action).toHaveBeenCalled();
  });
});
Comments