Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Created October 8, 2019 06:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/a9f681692051d9d5630ba5357c71ab22 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/a9f681692051d9d5630ba5357c71ab22 to your computer and use it in GitHub Desktop.
A React hook to create Axios Mocks

A simple hook which can be used to create Axios mock. The hook will throw an error if an unmocked route was found.

Works great in Storybook stories:

export const EmptyResult = () => {
  useMock((mock) => {
    const result = [];
    mock.onGet(searchUrl).reply(200, result);
  });

  return <MySearch query="abc" />;
};
import { useEffect } from 'react';
import axios, { AxiosRequestConfig } from 'axios';
import MockAdapter from 'axios-mock-adapter';
class MissingMock extends Error {
constructor({ method = 'get', url = '' }: AxiosRequestConfig) {
super(`Unhandled route in Axios mock: ${method.toUpperCase()} ${url}`);
this.name = 'MissingMock';
}
}
const mock = new MockAdapter(axios);
export function useMock(callback: (mock: MockAdapter) => void) {
useEffect(() => {
callback(mock);
mock.onAny().reply((config) => {
throw new MissingMock(config);
});
return () => mock.reset();
}, [callback]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment