Testing amplify Auth with Jest + Enzyme

Viewed 4876

I am very new to testing and I finally feel like I've got the hang of it. However, mocks are still a bit confusing. I am currently testing a signup function and the functions executes up until Auth.signUp. I'm not sure if I need to mock something in my test or if I need it to run through a different test.

async function signUp(
  { first, last, email, password }: SignupUserType,
  dispatch: Dispatcher,
  formContent: FormContentType,
  setFormContent: SetFormContent,
) {
  console.log('signing in init...');
  dispatch({ type: 'INIT' });

  try {
    const user = await Auth.signUp({
      username: email,
      password,
      attributes: {
        given_name: first,
        family_name: last,
        picture: userImage,
      },
    });
    console.log('sign up success!');
    dispatch({ type: 'STOP_LOADING' });
    console.log(formContent);
    setFormContent(formContent);
  } catch (err) {
    console.log('error signing up...', err);
    dispatch({ type: 'ERROR', error: err.message, doing: 'SIGNUP' });
  }
}

Test

import Amplify, { Auth } from 'aws-amplify';
import awsconfig from '../../../aws-exports';

Amplify.configure(awsconfig);

jest.mock('aws-amplify');
it('SIGNUP: Completed form fields enable button', async () => {
  ...
  wrapper
      .find('#submitButton')
      .at(0)
      .simulate('click');
 
  // thought I could do something like from https://stackoverflow.com/questions/51649891/how-to-mock-aws-library-in-jest
  Auth.signUp = jest.fn().mockImplementation(
   () => {
     // return whatever you want to test
  });

  // or I tried something like from https://markpollmann.com/testing-react-applications
  expect(Amplify.Auth.signUp).toHaveBeenCalled();
  // kept getting errors about not receiving the call 
})
3 Answers

I got it working!

import Amplify, { Auth } from 'aws-amplify';
import awsconfig from '../../../aws-exports';

Amplify.configure(awsconfig);


Auth.signUp = jest.fn().mockImplementation(
   () => {
     return true;
  });


it('SIGNUP: Completed form fields enable button', async () => {
  ...
  wrapper
      .find('#submitButton')
      .at(0)
      .simulate('click');
})

thanks for the tip!

However, in my case implementation of Auth.forgotPassword mock has to return new Promise, because in the code I use it like

Auth.forgotPassword(email)
     .then(...)
     .catch(...)

so my mock is:

Auth.forgotPassword = jest.fn().mockImplementation(() => {
  return new Promise((resolve, reject) => {
    resolve({
      CodeDeliveryDetails: {
        AttributeName: 'email',
        DeliveryMedium: 'EMAIL',
        Destination: 's***@y***.ru',
      },
    })
  })
})

Hope it helps someone who will stumble with the same issue

Another option would be to use:

jest.spyOn(Auth, "signUp").mockImplementation(() => {});

Through this you can omit jest.mock('aws-amplify'); and only need to import "Auth" and not Amplify itself

Related