How to test httpClient using axios using jest?
P粉659378577
P粉659378577 2023-09-15 20:55:32
0
1
714

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粉659378577
P粉659378577

reply all(1)
P粉575055974

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 });
    });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template