Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enzyme: How to test onSubmit function passed as prop?

I am fairly new with enzyme. I have two components under test.

form.jsx

const LoginForm = ({ style, handleSubmit }) => {
  return (
    <form onSubmit={handleSubmit}>
        <Button type='submit'>
          Login
        </Button>
    </form>
  );
};

LoginForm.propTypes = {
  handleSubmit: PropTypes.func.isRequired
};

I am using this component in another component as follows:

Component.jsx

export default class Login extends Component {
  constructor(props) {
    super(props);
    this.onLogin = this.onLogin.bind(this);
  }

  onLogin(event) {
    event.preventDefault();
    this.props.loginUser();
  }
  render() {
    return (
      <LoginForm style={loginFormStyles} handleSubmit={this.onLogin} />      
    );
  }
}

Login.propTypes = {
  auth: PropTypes.object.isRequired, //mapStateToProps
  loginUser: PropTypes.func.isRequired //mapDispatchToProps
};

I have written tests for form and they are passing.

form-test.js

 it('should have a onSubmit handler', () => {
      const props = {
        handleSubmit: () => {}
      };
      const wrapper = shallow(<LoginForm {...props} />);
      expect(_.isFunction(wrapper.props().onSubmit)).to.be.true;
    });

    it('should should call handlesubmit on form submission', () => {
      const handleSubmit = sinon.spy();
      const wrapper = shallow(<LoginForm handleSubmit={handleSubmit} />);
      wrapper.simulate('submit');
      expect(handleSubmit).to.have.been.called;
    });

These tests are passing. The confusing part is:

1- How do I test onLogin function in Component.jsx from form.jsx?

2- Vice versa, if I have to trigger onSubmit of form.jsx from component.jsx how would I do that?

like image 844
Umair Sarfraz Avatar asked Feb 07 '23 09:02

Umair Sarfraz


1 Answers

First of all, you can rename the Component.jsx to something else.

And for the test you can do something as below,

import Component from '../src/login';
import { stub } from 'sinon';


describe('login', () => {
  it('should call onsubmit', () => {
    const onSubmit = stub()
      .withArgs('username', 'password');
    const loginComponent = mount(<LoginForm  handleSubmit={onSubmit} /> );
    loginComponent.simulate('submit');
    expect(onSubmit.calledOnce).to.equal(true);
  });
});

I have not tested this but it is close to what you are looking at.

Update: I tested this and it is working.

like image 142
anoop Avatar answered Feb 09 '23 04:02

anoop