search

Home  >  Q&A  >  body text

How to test httpClient using axios using jest?

I have a service and sometimes I need to call an external API. To make this call easier to write, I created an httpService. Currently I only have a post method that receives the url and data.

import axios from 'axios'

const httpClient = axios.create({
  headers: {
    common: {
      'Content-Type': 'application/json'
    }
  }
})

export async function post(url, data) {
  try {
    const response = await httpClient.post(url, data)
    return response.data
  } catch (error) {
    console.log(error)
    throw new Error('Error in POST request')
  }
}

I need to write some tests for this code using jest, but since my url is generic, I want to pass a url like "http://test.com/api" and fake a positive result. How can I do this?

P粉659378577P粉659378577443 days ago713

reply all(1)I'll reply

  • P粉575055974

    P粉5750559742023-09-16 18:54:17

    You can use axios-mock-adapter package:

    For example

    import axios from 'axios';
    import MockAdapter from 'axios-mock-adapter';
    
    const mock = new MockAdapter(axios);
    
    describe('76630221', () => {
        test('should pass', async () => {
            const { post } = await import('./');
            mock.onPost('http://test.com/api').reply(200, {
                code: 0,
                message: null,
            });
            const data = await post('http://test.com/api', { name: 'nick' });
            expect(data).toEqual({ code: 0, message: null });
        });
    });

    reply
    0
  • Cancelreply