Guide to mocking axios in TypeScript when provided with a configuration

I encountered an issue with mocking axios when it uses the config convention `axios(passAConfigObj)`. I'm able to mock successfully when using `axios.get` or `axios.post`, but not with the former. I don't want to rely on a library for this task as I believe it can be accomplished without one.

I attempted to mock the request method that will be used with `axios.post`. When mocking axios and providing a return value, I received an error requesting an `AxiosPromise<any>`.

const mockedAxios = mocked(axios)

mockedAxios.mockImplementationOnce(() => Promise.resolve(2))

error: TS2322: Type 'Promise<number>' is not assignable to type AxiosPromise<any>

// auth.spec.ts
import { getAuthToken } from '../auth'

import axios from 'axios'
import { mocked } from 'ts-jest/utils'

jest.mock('axios')

describe('getAuthToken', () => {
  const mockedAxiosPost = mocked(axios)

  it('should return ', () => {
    mockedAxiosPost.mockImplementationOnce(() =>
      Promise.resolve({ data: 'response.data' })
    )

    const authToken = getAuthToken()

    expect(authToken).toEqual()
    expect(mockedAxiosPost).toHaveBeenCalledTimes(1)
    expect(mockedAxiosPost).toHaveBeenCalledWith()

  })
})
// auth.ts
import axios from 'axios'

export const getAuthToken = () => {

  const options = {
    url: `url`,
    method: 'POST',
    headers: {
      Authorization: ''
      'Content-Type': '',
    },
    data: {},
  }

  return axios(options)
    .then(response => {
      return response
    })
    .catch(error => {
      console.log(error.response)
    })
}

The goal is for axios, when passed a config, to internally call axios.post, thereby passing my test. While other implementations of axios.post and axios.get work with this testing style, this particular scenario poses a challenge. Although switching to axios.post would solve the issue, I am intrigued by finding a solution in this context. Thank you for your assistance :)

Answer №1

I've been facing this issue for about a year now, and by sheer luck, I stumbled upon this discussion while trying to find a solution.

After much contemplation, I finally managed to unravel the mystery.

To provide some background on how I tackled this problem:

I decided to mock the use of axios with jest, in a project that also utilizes Typescript.

Here's what ultimately worked for me:

__mocks__/axios.ts:

import { AxiosResponse } from 'axios';

const axiosResponse: AxiosResponse = {
  data: { falseProp: 'value' },
  status: 200,
  statusText: 'OK',
  config: {},
  headers: {},
};

export default {
  create: jest.fn((config) => {
     const wrapFunction = (param: any) => {
      return Promise.resolve(axiosResponse)
     }

     return wrapFunction
  })
};

This snippet illustrates how I was using axios in the code segment I needed to test:

src/MyRequestClass.ts:

import axios, { AxiosInstance, AxiosError } from 'axios'

const axiosInstance = axios.create({
  baseURL: 'https://fake-api-url',
  headers: {
      common: {
          Authorization: authToken
      }
  }
})

const request = {
  method: 'GET',
  url: 'https://fake-api-url/endpoint',
  params: {},
  data: {},
  headers: {}
}

const response = await axiosInstance(request)

In essence, I modified the create method to return a function that takes the config object (in my case, the request object) and consistently resolves the Promise.

Naturally, you could customize it further to make the Promise fail based on your specific testing scenarios.

I hope this explanation proves beneficial to anyone else grappling with a similar dilemma!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Simulating TypeDI service behavior in Jest

My current setup includes Node with TypeScript, TypeDI and Jest. I've been working on creating services that have dependencies on each other. For example: @Service() export class MainService{ constructor(private secondService: SecondService){} public ...

How to generate a new array in Angular by combining elements from two existing arrays for common items

I am currently working on a TypeScript function to compare two arrays and generate a third array containing the common items. For example: employees: any; offices: any; constructor() { this.employees = [ { fname: "John", lname: "James", sta ...

Using React for form validation

I'm facing a challenge while trying to develop a user registration form, especially when it comes to displaying form validation errors. Issues: 1) The input fails to post (via axios) to the database upon submission for inputs without errors. 2) The e ...

Replace string values with an object array for a particular property

When faced with the task of replacing specific string values defined by the user in an array of objects, but only applying the rules to certain properties, there is a need for a more efficient approach. For instance, consider the array below: [ {Name: &apo ...

Trying to enter the function, but it exits without executing

I'm facing an issue with my function that involves making multiple calls to an observer. I need the function to wait until all the calls are complete before returning. I attempted putting the return statement inside the subscribe method, but it result ...

Enabling cookie communication between NestJS server and Next.js frontend

I seem to be encountering challenges when trying to set cookies from a NestJS backend into my Next.js app. My NestJS application is running on port 3001 and here is my bootstrap setup: async function bootstrap() { const app = await NestFactory.create(Ap ...

ngIf failing to pick up on variable updates

Utilizing the greensock animation library to animate various components has presented a problem during the variable update within the onComplete function linked to a *ngIf. Strangely, Angular fails to recognize the variable update within the callback. Des ...

Trying out JSON ld script tag in a HEAD component of a Next.js application

Our project utilizes Next.js for development. We incorporate structured data in JSON-LD format using a script tag within the Next.js layout. Recently, we introduced the inclusion of this JSON-LD script tag conditionally. OurPage.tsx <Head> <tit ...

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

Why is the format incorrect when the Angular 7 (Change)-Function on Input of type Date isn't functioning?

I am facing an issue with updating the date using key input and assigning the selected date to a property of my object. Below is the code I'm currently working with: <input type="date" [value]="dateTime()" (change)="setDate($event)"/> The dat ...

The module does not contain 'toPromise' as an exported member in rxjs version 5.5.2

Encountering an error when using toPromise Prior method: import 'rxjs/add/operator/toPromise'; Updated approach: import { toPromise } from 'rxjs/operators'; The new way is causing the following issues: [ts] Module '"d:/.../ ...

A guide on testing the onClick() function and useState hooks with jest and enzyme

I'm relatively new to testing with jest and enzyme, and I'm facing challenges when it comes to covering functions like onClick(), useState variables, and useEffect(). Can someone who has experience in similar scenarios provide some guidance on ho ...

The attribute 'attribs' is not found on the 'Element' type in cheerio

When I run my code, I encounter an error that says Property 'attribs' does not exist on type 'Element'. It's puzzling to me why this error is being thrown. After examining the type definitions of cheerio, I discovered that attribs ...

Definitions provided for Redux (Toolkit) store including preloadedState

I'm currently working on setting up typings for configuring a Redux store with a preloaded state. While following the Redux Toolkit TypeScript quick start guide, I came across this example: import { configureStore } from '@reduxjs/toolkit' ...

Create a new project using Firebase Functions along with a Node.js backend and a React.js frontend

In the process of developing my application, I have chosen to utilize node.js, express.js, and Firebase with firebase functions, all coded in TypeScript. For the client side framework, I am interested in incorporating react.js. Currently, I have set up nod ...

Creating a versatile field duplication method in TypeScript

I have been trying to create a generic field copy function in TypeScript, but I am struggling to properly define the typing. Refer to method 4 in the code below. My main question is, how can I write a function that ensures TypeScript typing works correctly ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

AngularJS 2: Updating variable in parent component using Router

My current app.component looks like the following: import { Component, Input } from '@angular/core'; import {AuthTokenService} from './auth-token.service'; @Component({ selector: 'app-root', templateUrl: './app ...

An issue has arisen with the TypeScript function classes within the React Class, causing a compile error to be thrown

I am currently in the process of transitioning a React object from being a function to a class. This change is necessary in order to save the state and bind specific functions that I intend to pass to child components. Unfortunately, during compilation, I ...

How to utilize *ngFor alongside the async pipe for conditional rendering in Angular 8 HTML

.html <ng-container *ngFor="let contact of listContact | async; let index = index;"> <h6 class="title" *ngIf="contact && contact['type']"> {{contact['type']}} </h6> <div> {{conta ...