diff options
author | Martin Hanzel <martin@hanzel.io> | 2019-09-05 12:56:17 +0000 |
---|---|---|
committer | Paul Slaughter <pslaughter@gitlab.com> | 2019-09-05 12:56:17 +0000 |
commit | bd20aeb64c4eed117831556c54b40ff4aee9bfd1 (patch) | |
tree | 6a94bdd21bc56943f159e9422249c41a0713823c /spec/frontend/mocks | |
parent | 914af2f516acfa05cead52e438a35464abb4ac1d (diff) | |
download | gitlab-ce-bd20aeb64c4eed117831556c54b40ff4aee9bfd1.tar.gz |
Add helpers to wait for axios requests
Add two methods to the axios_utils Jest mock:
- `waitFor(url)`, which returns a Promise that resolves when the
next request to `url` finishes.
- `waitForAll()`, which returns a Promise that resolves when all
pending requests finish.
Diffstat (limited to 'spec/frontend/mocks')
-rw-r--r-- | spec/frontend/mocks/ce/lib/utils/axios_utils.js | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/spec/frontend/mocks/ce/lib/utils/axios_utils.js b/spec/frontend/mocks/ce/lib/utils/axios_utils.js index a3783b91f95..85fad231d28 100644 --- a/spec/frontend/mocks/ce/lib/utils/axios_utils.js +++ b/spec/frontend/mocks/ce/lib/utils/axios_utils.js @@ -1,3 +1,5 @@ +import EventEmitter from 'events'; + const axios = jest.requireActual('~/lib/utils/axios_utils').default; axios.isMock = true; @@ -13,4 +15,64 @@ axios.defaults.adapter = config => { throw error; }; +// 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 +const onResponse = config => { + activeRequests -= 1; + setImmediate(() => { + events.emit('response', config); + }); +}; + +const subscribeToResponse = (predicate = () => true) => + new Promise(resolve => { + 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. + setImmediate(listener); + }); + +/** + * Registers a callback function to be run after a request to the given URL finishes. + */ +axios.waitFor = url => subscribeToResponse(({ url: configUrl }) => configUrl === url); + +/** + * 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; + +axios.interceptors.request.use(config => { + onRequest(); + return config; +}); + +// Remove the global counter +axios.interceptors.response.use( + response => { + onResponse(response.config); + return response; + }, + err => { + onResponse(err.config); + return Promise.reject(err); + }, +); + export default axios; |