debian-mirror-gitlab/spec/frontend/__helpers__/mocks/axios_utils.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

81 lines
2.1 KiB
JavaScript
Raw Normal View History

2019-12-04 20:38:33 +05:30
import EventEmitter from 'events';
2019-09-30 21:07:59 +05:30
const axios = jest.requireActual('~/lib/utils/axios_utils').default;
axios.isMock = true;
// Fail tests for unmocked requests
2021-03-08 18:12:59 +05:30
axios.defaults.adapter = (config) => {
2019-09-30 21:07:59 +05:30
const message =
`Unexpected unmocked request: ${JSON.stringify(config, null, 2)}\n` +
2019-12-04 20:38:33 +05:30
'Consider using the `axios-mock-adapter` module in tests.';
2019-09-30 21:07:59 +05:30
const error = new Error(message);
error.config = config;
2019-12-04 20:38:33 +05:30
global.fail(error);
2019-09-30 21:07:59 +05:30
throw error;
};
2019-12-04 20:38:33 +05:30
// Count active requests and provide a way to wait for them
let activeRequests = 0;
const events = new EventEmitter();
const onRequest = () => {
activeRequests += 1;
};
// Use setImmediate to alloow the response interceptor to finish
2021-03-08 18:12:59 +05:30
const onResponse = (config) => {
2019-12-04 20:38:33 +05:30
activeRequests -= 1;
2022-05-07 20:08:51 +05:30
// eslint-disable-next-line no-restricted-syntax
2019-12-04 20:38:33 +05:30
setImmediate(() => {
events.emit('response', config);
});
};
const subscribeToResponse = (predicate = () => true) =>
2021-03-08 18:12:59 +05:30
new Promise((resolve) => {
2019-12-04 20:38:33 +05:30
const listener = (config = {}) => {
if (predicate(config)) {
events.off('response', listener);
resolve(config);
}
};
events.on('response', listener);
// If a request has been made synchronously, setImmediate waits for it to be
// processed and the counter incremented.
2022-05-07 20:08:51 +05:30
// eslint-disable-next-line no-restricted-syntax
2019-12-04 20:38:33 +05:30
setImmediate(listener);
});
/**
* Registers a callback function to be run after a request to the given URL finishes.
*/
2021-03-08 18:12:59 +05:30
axios.waitFor = (url) => subscribeToResponse(({ url: configUrl }) => configUrl === url);
2019-12-04 20:38:33 +05:30
/**
* Registers a callback function to be run after all requests have finished. If there are no requests waiting, the callback is executed immediately.
*/
axios.waitForAll = () => subscribeToResponse(() => activeRequests === 0);
axios.countActiveRequests = () => activeRequests;
2021-03-08 18:12:59 +05:30
axios.interceptors.request.use((config) => {
2019-12-04 20:38:33 +05:30
onRequest();
return config;
});
// Remove the global counter
axios.interceptors.response.use(
2021-03-08 18:12:59 +05:30
(response) => {
2019-12-04 20:38:33 +05:30
onResponse(response.config);
return response;
},
2021-03-08 18:12:59 +05:30
(err) => {
2019-12-04 20:38:33 +05:30
onResponse(err.config);
return Promise.reject(err);
},
);
2019-09-30 21:07:59 +05:30
export default axios;