Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test form submit in React?

I have the following React component:

export default class SignUpForm extends React.Component {
    ...
    doSignupForm(event) {
        // Some API call...
    }

    render() {
        return (
            <div>
                <form action="/" onSubmit={this.doSignupForm.bind(this)} id="register-form">
                    <button type="submit" id="register_button">Sign Up</button>
                </form>
            </div>
        );
    }
};

I want to test that the button fires the doSignupForm function - how do I do this (ideally using Mocha/Chai/Enzyme/Sinon)?

In addition, as you can see the doSignupForm function fires an API call - should this API call be tested seperately using an integration test (?).

like image 897
JoeTidee Avatar asked Mar 07 '17 01:03

JoeTidee


People also ask

How do I submit form data to API in React JS?

Create the form data hook Create a new file called UseForm. js in the src folder. The hook will intercept regular form submit and will send JSON data to the API endpoint.


1 Answers

You can simulate form submission using React Utils:

var rendered = TestUtils.renderIntoDocument(SignupForm);
var form = TestUtils.findRenderedDOMComponentWithTag(rendered, 'form');
TestUtils.Simulate.submit(form);

Also, testing calls to the actual API is not reliable, you should mock the API call with responses you expect from it, an idea would be to extract the API call in to its own module, and setup an spy to test the behaviour of your component with an specific response (example spy with Jasmine):

spyOn(apiModule, "requestProjects").and.callFake(function() {
    return { ...someProjects };
});

Reference:

https://facebook.github.io/react/docs/test-utils.html https://volaresystems.com/blog/post/2014/12/10/Mocking-calls-with-Jasmine

like image 177
Carlos Martinez Avatar answered Sep 17 '22 18:09

Carlos Martinez