jeudi 28 mai 2020

How to test/mock API calls using JEST in Create react app

Hello I'm trying to test my async action creators in create react app but I don't have enough information to fix the issue. This is my first time to test async actions in react. I'm using axios for fetching API and jest mock to create a mock functions.

Here's fetch function:

export async function signUpAPI(userSignupInfo: ILoginSignUpFormParams): Promise<ILoginSignupResponse> {
  const { username, email, password } = userSignupInfo;
  try {
    const res = await axiosInstance.post('/signup', {
      username,
      email,
      password
    });
    return res.data;
  } catch (error) {
    throw error.response.data;
  }
}

here's my test:

import * as sessionActions from '../Actions';
import { sessionInitialState } from 'models/Session/sessionInitialState';
import { SessionActionTypes } from '../Types';
import axios from 'axios';
import { signUpAPI } from 'api/sessions';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('Session Action Test', () => {
  describe('async ACTION Test', () => {
    describe('On signup', () => {
      it('should success response on signup', async () => {
        mockedAxios.post.mockResolvedValue({ data: {} });

        const t = await signUpAPI({ username: 'yousir1', password: 'Password1!', email: 'yousir1@gmail.com' });
        console.log(t);
      });
    });
  });
});

Here's the error that I'm getting but dont understand because I am mocking it as a Resolved value but it goes to my catch block in my actual API call. Weird.

enter image description here

Aucun commentaire:

Enregistrer un commentaire