Search code examples
reactjsjestjsreact-hooksaws-amplify

How to test amplify auth signup in react using Jest + Enzyme?


I need to test the register method along with the amplify auth signup which is written in my action file.

import history from "../utils/history.helper";
import { alertInfo } from "../utils/common.helper";
import { Auth } from "aws-amplify";

export const AuthAction = {
  register,
};

function register(signUpData) {
  return async (dispatch) => {
    const {
      username,
      password,
      company_name,
      country_name,
      designation,
    } = signUpData;
    try {
      const signUpResponse = await Auth.signUp({
        username,
        password,
        attributes: {
          "custom:company_name": company_name,
          "custom:country_name": country_name,
          "custom:designation": designation,
        },
      });

      alertInfo("success", "Please verify the mail,for successfull login");
      history.push("/login");
    } catch (error) {
      alertInfo("error", error.message);
    }
  };
}]

This action file I'm calling from my signup component

import React from "react";
import { useForm } from "react-hook-form";
import { useDispatch } from "react-redux";
import { yupResolver } from "@hookform/resolvers/yup";

import content from "./content";
import { AuthInputField } from "../../common/FieldComponent";
import { AuthAction } from "../../../actions/auth.action";
import { signupSchema } from "../../common/Validation";

const SignupForm = () => {
  const dispatch = useDispatch();
  const { register, handleSubmit, errors } = useForm({
    resolver: yupResolver(signupSchema),
  });
  const [buttonDisable, setButtonDisable] = React.useState(false);
  function onSubmit(signUpData) {
    setButtonDisable(true);
    dispatch(AuthAction.register(signUpData));
  }
  return (
    <div className="container" data-test="signUpContainer">
      <h4>Welcome</h4>
      <p>Please resigter to your account.</p>
      <form data-testid="submit" onSubmit={handleSubmit(onSubmit)}>
        {content.inputs.map((input, index) => {
          return (
            <AuthInputField
              key={index}
              name={input.name}
              label={input.label}
              placeholder={input.placeholder}
              type={input.type}
              register={register}
              error={(errors && errors[input.name] && errors[input.name]) || {}}
            />
          );
        })}

        <input
          type="submit"
          className="btn btn-primary button"
          name="submit"
          value={`Submit`}
          role="submit"
          disabled={buttonDisable}
        />
      </form>
    </div>
  );
};

export default SignupForm;

I'm trying to find a way for testing the "Auth.signup" but didn't find any specific solution.


Solution

  • After spending so many hours, finally wrote these test cases for the above question.

    import { register } from "./auth.action";
    import mockData from "./__mocks__/mockData";
    import { Auth } from "./__mocks__/aws-amplify";
    import history from "../utils/history.helper";
    jest.mock("./auth.action", () => {
      return { register: jest.fn(() => mockPromise) };
    });
    
    jest.mock("aws-amplify");
    describe("Signup action", () => {
      beforeEach(() => {
        register.mockClear();
      });
      test("Check register function have been called or not", async () => {
        register();
        expect(register).toHaveBeenCalled();
        expect(register).toMatchSnapshot();
      });
    
      test("Check args passed in function are valid or not", () => {
        expect(mockData.signupData).not.toBeNull();
        expect(mockData.signupData).toMatchObject({
          username: "Abhinav02@getnada.com",
        });
        expect(mockData.signupData).toHaveProperty("company_name", "Ces");
        expect(mockData.signupData).toHaveProperty("country_name", "India");
        expect(mockData.signupData).toHaveProperty("designation", "SD");
        expect(mockData.signupData).toHaveProperty("password", "Password@123");
    
        expect(mockData.signupData).toMatchSnapshot();
      });
    
      test("Amplify auth is called or not", () => {
        Auth.signUp(mockData.signupData);
        expect(Auth.signUp).toHaveBeenCalled();
        expect(Auth.signUp).toMatchSnapshot();
      });
    
      test("history is pushed", () => {
        const pushSpy = jest.spyOn(history, "push");
    
        pushSpy("/login");
    
        expect(pushSpy).toHaveBeenCalled();
        expect(pushSpy.mock.calls[0][0]).toEqual("/login");
    
      });
    });
    

    I have written the amplify auth test case in mock file.

        // in __mocks__/aws-amplify.js
    export const Auth = {
      currentSession: jest.fn(() => Promise.resolve()),
      signUp: jest.fn(() => Promise.resolve()),
      signIn: jest.fn(() => Promise.resolve()),
    };
    

    Hope it helps others as well who are looking for the same.