By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
rocoderesrocoderes
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Notification Show More
Latest News
How to set the dropdown value by clicking on a table row
Javascript – How to set the dropdown value by clicking on a table row
JavaScript
Attempting to increase the counter, when the object's tag exist
Javascript – Attempting to increase the counter, when the object’s tag exist
JavaScript
Cycle2 JS center active slide
Javascript – Cycle2 JS center active slide
JavaScript
Can import all THREE.js post processing modules as ES6 modules except OutputPass
Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass
JavaScript
How to return closest match for an array in Google Sheets Appscript
Javascript – How to return closest match for an array in Google Sheets Appscript
JavaScript
Aa
Aa
rocoderesrocoderes
Search
  • Home
  • HTML & CSS
    • Login and Registration Form
    • Card Design
    • Loader
  • JavaScript
  • Python
  • Internet
  • Landing Pages
  • Tools
    • Google Drive Direct Download Link Generator
    • Word Count
  • Games
    • House Painter
Follow US
High Quality Design Resources for Free.
rocoderes > JavaScript > Javascript – Mock axios get request returning back undefined response
JavaScript

Javascript – Mock axios get request returning back undefined response

Admin
Last updated: 2023/12/23 at 5:16 AM
Admin
Share
2 Min Read
Mock axios get request returning back undefined response

Problem:

My jest test mock of an axios get returns back undefined as the response and I am not sure what I am doing wrong?

Contents
Problem:Solution:

My component that has the axios call is shown below:

import {AgGridReact} from "ag-grid-react";
import React, {useEffect, useState, useMemo} from 'react';

useEffect(() => {
  if(searchObject)
    console.log("new being fetched")
  fetchResults(gridApi);
}, [searchObject]);

const fetchResults = (paramsApi) => {
  Service()
  .getResults(searchObject)
  .then((response) => {
    console.log("calling.....", response); // undefined for response, why?
    let results = response.data.results;
    // more code below but unnecessary to show since response is undefined

Jest test class:

import * as React from 'react';
import { screen } from '@testing-library/dom';
import { render } from '@testing-library/react';
import AgGridResults from "./AgGridResults";

describe('AgGridResults', () => {
  beforeEach(async () => {
    jest.mock("../../service/Service", () => ({
      __esModule: true,
      default: () => ({
        getResults: async () => ({
          data: { results: { M0: { value: ["Source ID"] } } },
        }),
      }),
    }));
    render(<AgGridResults searchObject={...} />);
    await waitFor(() => expect(screen.getByText('Actions')).toBeInTheDocument())
  });

  test('AgGridResults', () => {
    expect(screen.getByText('Actions')).toBeInTheDocument();
  });
});

import axios from 'axios';
import UrlUtility from './urlUtility';

function Service() {
  return {
    getResults: async (searchObject) => {
      let urlString = UrlUtility().convert(searchObject);
      if (searchObject && urlString) {
        return await axios.get('/api/' + urlString + '&pageLength=50');
      }
    },
    getAgreementTypes: async (searchTerm) => {
      return await axios.get('/api/' + 'searchString=' + searchTerm);
    },
  };
}

export default Service;

Solution:

Mocking Axios when your component doesn’t actually use it creates a brittle coupling. If you ever changed the Service implementation, your tests would break.

I would instead mock Service for your component test

jest.mock("./path/to/service", () => ({
  __esModule: true,
  default: () => ({
    getResults: async () => ({
      data: { results: { M0: { value: ["Source ID"] } } },
    }),
  }),
}));

Related

Subscribe to Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Share this Article
Facebook Twitter Email Print
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article JavaScript - check if any radio button inputs = no [duplicate] Javascript – JavaScript – check if any radio button inputs = no [duplicate]
Next Article Issue with Synchronization Between CSS Transition and JavaScript Update on Element Click Javascript – Issue with Synchronization Between CSS Transition and JavaScript Update on Element Click
Leave a comment Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

- Advertisement -

You Might Also Like

How to set the dropdown value by clicking on a table row

Javascript – How to set the dropdown value by clicking on a table row

February 11, 2024
Attempting to increase the counter, when the object's tag exist

Javascript – Attempting to increase the counter, when the object’s tag exist

February 11, 2024
Cycle2 JS center active slide

Javascript – Cycle2 JS center active slide

February 10, 2024
Can import all THREE.js post processing modules as ES6 modules except OutputPass

Javascript – Can import all THREE.js post processing modules as ES6 modules except OutputPass

February 10, 2024
rocoderesrocoderes
Follow US

Copyright © 2022 All Right Reserved By Rocoderes

  • Home
  • About us
  • Contact us
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc.

Zero spam, Unsubscribe at any time.
Welcome Back!

Sign in to your account

Lost your password?