christianalfoni / formsy-react

A form input builder and validator for React JS
MIT License
2.6k stars 436 forks source link

Fill and submit form in jest test #495

Closed AdrienLemaire closed 6 years ago

AdrienLemaire commented 6 years ago

Anyone know how to properly simulate filling form inputs, then submit the form and checking that the onValidSubmit method has been properly called with the expected values, using jest and enzyme ?

Have been digging in the code for half a day, but couldn't figure this on. Here's a test I'd expect to work:

describe("EmailLoginForm", () => {
  const mockStore = configureStore();

  const initialState = {
    firebase: {
      login: jest.fn((email, password) => Promise.resolve()),
    },
  };
  const initialContext = {
    store: mockStore(),
  };
  // dive in Formsy
  const wrapper = shallow(<EmailLoginForm {...initialState} />, {
    context: initialContext,
  }).dive();

  it("should render properly", () => {
    expect(wrapper).toMatchSnapshot();
  });

  it("can trigger a login action", () => {
    const form = wrapper.find("Formsy");
    form.simulate("change", {email: "a@a.com", password: "password"}, true);
    form.find(".submit-btn").simulate("click");
    expect(initialState.firebase.login).toHaveBeenCalledWith(
      "a@a.com",
      "password",
    );
  });

Using a regular formsy form behind:

          <Formsy
            name="login_form"
            onValidSubmit={this.doSubmit}
            onValid={enableButton}
            onInvalid={disableButton}
          >
            <Input
              type="text"
              name="email"
              validations="isEmail"
              required
            />
            <Input
              type="password"
              name="password"
              required
            />
            <FlatButton
              type="submit"
              className="submit-btn login-submit"
              disabled={!canSubmit}
              secondary
            />
          </Formsy>

I understand that enzyme simulate("change") (doc) method will call the element's related onChange method, which Formsy implements. Since formsy onChange expects 2 variables currentValues and isChanged, I passed them to the simulate method. If overriding the onChange method in my component, I can see that the function is properly called. That confirms the fact that my simulate call is done properly.

Yet, my doSubmit method never gets called on onValidSubmit (or onSubmit for that matter). When debugging my elements, the inputs values stay undefined, hence they never got updated.

Any help will really be appreciated Cordially

AdrienLemaire commented 6 years ago

@christianalfoni looking forward to your reply :)

twisty commented 6 years ago

Hi, this repo has moved to https://github.com/formsy/formsy-react - can you recreate your issue there please.