Skip to content

Instantly share code, notes, and snippets.

@pakman198
Created August 22, 2020 18:02
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 pakman198/befaad5b472a2fd09234bd059c791eae to your computer and use it in GitHub Desktop.
Save pakman198/befaad5b472a2fd09234bd059c791eae to your computer and use it in GitHub Desktop.
axios interceptors
import axios from 'axios';
export const experimentsInterceptor = () => {
const getExperiments = () => {
const [, params] = window.location.search.split('?');
const experiments = params.split('ex.');
const values = experiments.reduce((tally, item) => {
if (item.match(/^[A-Z][A-Z][A-Z]\d\d/)) {
const newItem = item.replace('&', '');
tally.push(newItem);
}
return tally;
}, []);
const set = new Set(values);
return [...set];
};
axios.interceptors.request.use(
config => {
const experiments = getExperiments();
if (experiments.length !== 0) {
config.headers['my-custom-header'] = experiments.join(',');
}
return config;
},
error => {
// Do something with request error
return Promise.reject(error);
}
);
};
import axios from 'axios';
import axiosMock from 'jest-mock-axios';
describe('experimentInterceptor', () => {
const BASE_URL_WITH_PARAMS = 'http://localhost:3000/some_route/child_route?q=something&ex.RGB00=2&ex.ABC99=3';
const API_ENDPOINT = 'http://localhost:9000/some_route';
beforeEach(() => {
axiosMock.reset();
});
it('should add my-custom-header header to any api request when the URL has experiment params', async () => {
mockWindow(BASE_URL_WITH_PARAMS);
experimentsInterceptor();
axiosMock.get(API_ENDPOINT);
const config = await axios.interceptors.request.handlers[0].fulfilled({
url: API_ENDPOINT,
headers: {}
});
expect(config.headers).toEqual({
'my-custom-header': 'RGB00=2,ABC99=3'
});
});
});
const mockWindow = search => {
Object.defineProperty(global, 'window', {
value: {
location: {
search
}
},
writable: true
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment