42

Mock Axios requests in Storybook

 2 years ago
source link: https://gist.github.com/rafaelrozon/ed86efbea53094726e162dc05882cddc
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Mock Axios requests in Storybook · GitHub

Instantly share code, notes, and snippets.

Mock Axios requests in Storybook

This comes when I tried to do the above. Any idea?

utils.js:117 Uncaught (in promise) Error: Request failed with status code 404
at createErrorResponse (utils.js:117)
at Object.settle (utils.js:97)
at handleRequest (handle_request.js:78)
at index.js:18
at new Promise ()
at MockAdapter. (index.js:17)
at dispatchRequest (dispatchRequest.js:59)

Found this answer while I was trying to mock axios inside of my stories, ran into an issue when I added multiple stores (that 404 error that @husni1992 mentions) it was basically an issue with the mocks colliding.

I ended working around it creating a helper component, which does the mocking.

Helper component:

import { useEffect } from 'react';
import MockAdapter from 'axios-mock-adapter';
import { api } from '../../services'; // This is an AxiosInstance

interface IProps {
  children: any;
  mock: (adapter: MockAdapter) => void;
}

const apiMock = new MockAdapter(api);

const AxiosMock = ({ children, mock }: IProps) => {
  useEffect(() => {
    mock(apiMock);
    return () => {
      apiMock.reset();
    };
  });
  return children;
};

export default AxiosMock;

Usage in stories:

export const Default = () => {
  const mock = (apiMock: MockAdapter) => {
    apiMock.onGet('/api/meetings/1').reply(200, {
      id: 1,
      title: 'A Meeting',
    });
  };
  return (
    <AxiosMock mock={mock}>
      <Meeting />
    </AxiosMock>
  );
};

I'm using Storybooks CSF

Initially I used example above and got same erors.
Moved const mock = new MockAdapter(axios); inside story and error is gone.

Be aware that if you use your own Axios instance you should mock that instance, not the imported one

const axios = require('axios');
const axiosInstance = axios.create({
    timeout: 30000
});
const mock = new MockAdapter(axiosInstance);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK