Jest how to check spy function being called within a spy function?

Viewed 1567

Consider the following react component.

import React, { Component } from "react";
import { reduxForm, Field } from "redux-form";
import { connect } from "react-redux";
import formFields from "components/Login/formFields";
import LoginField from "components/Login/LoginField/LoginField";
import _ from "lodash";
import { loginFormSubmit } from "store/actions/profile/profile";
import { SubmissionError } from "redux-form";

export class Login extends Component {
  renderFields() {
    return _.map(formFields, ({ label, name }) => {
      return (
        <Field
          component={LoginField}
          type="text"
          key={label}
          label={label}
          name={name}
        />
      );
    });
  }

  render() {
    const { handleSubmit, history } = this.props;
    return (
      <div>
        <form
          onSubmit={handleSubmit(values =>
            loginFormSubmit(values, history, SubmissionError)
          )}
        >
          {this.renderFields()}
          <button type="submit">Send the Survey</button>
        </form>
      </div>
    );
  }
}
export default connect(
  null,
  { loginFormSubmit }
)(
  reduxForm({
    form: "loginform"
  })(Login)
);

You can see the handleSubmit is called when the form is submitted. handleSubmit calls our custom loginFormSubmit from redux. how can I check loginFormSubmit is called within handleSubmit. Here is my test so far

import { Login } from "components/Login/Login";
import { shallow } from "enzyme";
import React from "react";

describe("The Login component description", () => {
  describe("The Login component", () => {
    const props = {
      handleSubmit: jest.fn()
    };
    it("should call handleSubmit on form submission", () => {
      const wrapper = shallow(<Login {...props} />);
      wrapper.find("button").simulate("click");
      expect(props.handleSubmit).toHaveBeenCalled();
    });
  });
});
1 Answers

The module the function is imported from should be mocked at the top of the test:

import { loginFormSubmit } from "store/actions/profile/profile";

jest.mock('store/actions/profile/profile', () => ({ loginFormSubmit: jest.fn() }));

Then it can be asserted:

 expect(props.handleSubmit).toHaveBeenCalledWith(expect.any(Function));
 expect(loginFormSubmit).not.toHaveBeenCalled(...);
 props.handleSubmit.mock.calls[0][0]()
 expect(loginFormSubmit).toHaveBeenCalledWith(...);
Related