How do i write test case for API call on componentDidMount Using Jest enzyme

Viewed 267

I want to write a test case for await API call on componentDidMount for success and error.

I added code behavioral of the API call please suggest test case implementation for that.

import {apiService} from './../../../_services'
import { Component } from 'react';


class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contentId: 123,
      userID: 1345
    };
  }
  componentDidMount() {
    this.getMappedContent()
      .then(content => {
        if (content) {
          if (content.contentData && content.contentData.isLocked) {
            if (content.contentData.lockedByEmail !== this.state.userID) {
              this.setState({ isLocked, lockedBy })
            }
          }
          this.setState({users: content.contentData})
        }
      })
      .catch(error => {
      })
  }

  getMappedContent = async () => {
    if (!this.state.contentId) {
      return;
    }
    const requestParams = {
      contentId: this.state.contentId,
    };
    //getting existing mapContent item if exist
    return await apiService.getUser(requestParams);
  };
}

// apiService.js Here is my API service Code, please suggest me to write a test case in case of success and failure

import Config from "./config";
import axiosInstance from "./axiosInstancs";

    const getUser = (params) => {
     const query = createQuery(params);
     const url = `${Config.users}${query ? query : ''}`
       return axiosInstance.get(url)
        .then(response => {
           return response.data.data;
         })
        .catch(error => {
          return false;
       });
    }
export const apiService = {
  getUser
}

Here what I tried to write a test case for success and failure please suggest what more I can improve in this?

it('Should success API call with contentId', async () => {
        const expectedPosts = [
          {id: 1, title: 'test1'},
          {id: 2, title: 'test2'},
        ]
        const mock = jest.fn().mockReturnValue(expectedPosts);
        apiService.getUser = mock;
        const result = await apiService.getUser({contentId: 134});
        expect(result).toBe(expectedPosts);
     })

     it('Should not success API call without contentId', async () => {
        const expectedPosts = []
        const mock = jest.fn().mockReturnValue(expectedPosts);
        apiService.getUser = mock;
        const result = await apiService.getUser({});
        expect(result).toBe(expectedPosts);
     })
0 Answers
Related