ctimmerm / axios-mock-adapter

Axios adapter that allows to easily mock requests
MIT License
3.46k stars 245 forks source link

assert that Axios get has been called with the correct URL #256

Closed swapnildubal closed 4 years ago

swapnildubal commented 4 years ago

How do I test if the Axios get has been called with the correct URL:

test('should hit correct endpoint and fetch data successfully', async () => { const mockData = { data: { fname: 'test' } }; mock.onGet().reply(200, mockData); const res = await NetworkUtils.makeApiRequest('get', 'http://test.com'); expect(axios.get).toHaveBeenCalledWith('http://test.com'); });

pmgmendes commented 4 years ago
test('should hit correct endpoint and fetch data successfully', () => {

    const mockData = { data: { fname: 'test' } };

    mockAxios.onGet('http://test.com').reply((config) => {
      expect(config.url).toBe('http://test.com');
      expect(config.headers).toEqual(); // assert the headers

      return [ 200, mockData ];
    });

    return NetworkUtils.makeApiRequest('get', 'http://test.com').then((response) => {
      expect(response.status).toBe(200);
      expect(response.data).toEqual(mockData);
    });
});
bratanon commented 3 years ago

This does not work as expected for me.

If a expect in the reply-callback fails, I'm left with a blank error.

This is how I solved it (typescript)

test('should hit correct endpoint and fetch data successfully', async () => {

    const mockData: any = { data: { fname: 'test' } };
    let requestConfig: AxiosRequestConfig;

    mockAxios.onGet('http://test.com').reply((config): Promise<any[]> => {
      requestConfig = config;
      return Promise.resolve([200, mockData]);
    });

    const response = await  NetworkUtils.makeApiRequest('get', 'http://test.com');
    expect(response.status).toBe(200);
    expect(response.data).toEqual(mockData);

    expect(requestConfig.url).toBe('http://test.com');
    expect(requestConfig.headers).toEqual(); // assert the headers
});