Szustka124
Szustka124

Reputation: 91

My react app works correctly, but tests not

Unit test returns error, but when I launch my app everything works.

The problem is, that when callOnSubmitWithData() is returned in arrow function as onPress callback, mocked onSubmit function is not called, but in launched app everything works.

Unit test in Jest with enzyme:

const setup = (propOverrides) => {
	const props = Object.assign({
		fields: [],
		error: '',
		onSubmit() {}
	}, propOverrides);

	const wrapper = shallow(
			<Form {...props}/>
	);

	return {
		props,
		wrapper
	};
};

it('sends fields data to callback after push submit button', () => {
  const inputValue = 'Some text';
  const submitCallback = jest.fn();

  const {wrapper, props} = setup({
    onSubmit: submitCallback,
    fields: [
      {
        key: 'first',
        value: inputValue
      },
      {
        key: 'second',
        value: inputValue
      }
    ]
  });

  const output = {
    [props.fields[0].key]: inputValue,
    [props.fields[1].key]: inputValue
  };

  wrapper.setState({isSubmitDisabled: false});
  wrapper.update();
  wrapper.find(Button).simulate('click');

  expect(submitCallback).toHaveBeenCalledWith(output);
});

And my part of my component:

class Form extends React.Component {
	constructor(props) {
		super(props);

    //Create State
    
    //Other bindings
		this.callOnSubmitWithData = this.callOnSubmitWithData.bind(this);
	}
  
  //...
  
	callOnSubmitWithData() {
		const data = this.extractFieldsData();
		this.props.onSubmit(data);
	}

	extractFieldsData() {
		//Returns object with all fields values
	}

	render() {
		const {fields, error, buttonTitle} = this.props;

		return (
			<View>
				<View>
				{
					fields.map((data) => {
						//...
						return (<AuthTextInput/>);
					})
				}
				</View>

				<Button 
					title={buttonTitle}
					onPress={() => this.callOnSubmitWithData()}
					disabled={this.state.isSubmitDisabled}
				/>
			</View>
		);
	}
}

export default Form;

Upvotes: 1

Views: 58

Answers (1)

skyboyer
skyboyer

Reputation: 23705

The reason is simulate(). You attach handler to onPress but calling simulate('click').

You need to call exactly onPress. Maybe simulate('press') will work.

If not you can just

wrapper.find(Button).props().onPress();
wrapper.update();

and then your mock will be run.

Upvotes: 1

Related Questions