Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock and test Axios rejected promise?

I created a class called API and it's a simple wrapper around Axios

export class API {    
  static get = async (route: string, version: string = API_VERSION) => {
    try {
      return await axios.get(`${BASE_URL + version}${route}`);
    } catch (error) {
      throw error;
    }
  };
}

I'm trying to test the catch branch of the get method:

I tried:

describe('API Throws Errors', () => {
  beforeEach(() => {
    // axios.get.mockImplementation(() => Promise.reject('rejected'));
    jest.mock('axios', () => ({
      get: jest.fn().mockReturnValue(Promise.reject('error'))
    }));
  });

  it('get fails', async () => {
    await expect(() => {
      API.get(GROUPS.url());
    }).rejects.toEqual('error');
  });

  afterEach(() => {
    jest.clearAllMocks();
  });
});

enter image description here

like image 501
Batman Avatar asked Oct 16 '25 06:10

Batman


1 Answers

You can mock behaviour of axios.get by using jest.mock. Put the below code above the describe section:

jest.mock('axios', () => ({
  get: jest.fn().mockReturnValue(Promise.reject('error'))
}));

And you test the error like below:

it('get fails', async () => {
    await expect(API.get("bad_url")).rejects.toEqual('error');
});

Exact Code

jest.mock('axios', () => ({
    get: jest.fn().mockReturnValue(Promise.reject('error')),
}));

describe('API Throws Errors', () => {
    it('get fails', async () => {
        await expect(API.get(GROUPS.url())).rejects.toEqual('error');
    });
});

Note:

If you have another test case that shouldnt be failed, you can just mock it to return Promise.resolve(). Or you can just simple clear the mock.

describe('API Throws Errors', () => {
    it('get fails', async () => {
        await expect(API.get(GROUPS.url())).rejects.toEqual('error');
    });
    
    it('should success', async () => {
        Axios.get.mockReturnValue(Promise.resolve(SOME_VALUE));
        await expect(API.get(GROUPS.url())).resolves.toEqual(SOME_VALUE);
    });
});
like image 129
topmoon Avatar answered Oct 18 '25 22:10

topmoon



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!