Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an AxiosError object for test purpose

I am looking for a way to easily create AxiosError (from the axios lib itself or an external helper)

The context.

I have this function that I want to test.

import { AxiosError } from 'axios';

export function isEmailConflict({ error }: { error: AxiosError<{ type?: string; message?: string }> }) {
// ...
}

So far I performed it in this way

import { AxiosError } from 'axios';
// ...
  describe('isEmailConflict', () => {
    function newConflicError(): AxiosError {
      return {
        isAxiosError: true,
        name: '',
        message: '',
        toJSON: () => ({}),
        config: {},
        response: {
          data: { type: 'aa', message: 'bb' },
          status: 409,
          statusText: 'Conflict',
          headers: {},
          config: {},
        },
      };
    }

    it('should return true if the passed error is of type email already used', () => {
      const error = newConflicError();
      //...
    });

but I find it ugly, is there an easy way to create an AxiosError ?

I already tried ts-auto-mock but I find it too intrusive in my tests config.

like image 493
Julien TASSIN Avatar asked Dec 04 '25 17:12

Julien TASSIN


1 Answers

From axios v1.0.0, it added the AxiosError to AxiosStatic, see PR.

// Expose AxiosError class
axios.AxiosError = require('../lib/core/AxiosError');

This means you can import the AxiosError class from axios module and create an axios error instance directly. It may be useful for testing.

E.g. (using axios 1.3.4)

import { AxiosError, AxiosHeaders } from "axios";

var request = { path: "/foo" };
const headers = new AxiosHeaders();
const config = {
  url: "http://localhost:3000",
  headers
};
var error = new AxiosError("Boom!", "ESOMETHING", config, request, {
  status: 200,
  data: { foo: "bar" },
  statusText: "ok",
  config,
  headers
});

console.log("axios error: ", error);

export function isEmailConflict(error: AxiosError) {
  // ...
}
isEmailConflict(error);

codesandbox

like image 163
slideshowp2 Avatar answered Dec 06 '25 13:12

slideshowp2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!