Welcome to mirror list, hosted at ThFree Co, Russian Federation.

axios_utils.js « utils « lib « ce « mocks « frontend « spec - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 85fad231d28c349e5a3a035fe5c3432823f04360 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import EventEmitter from 'events';

const axios = jest.requireActual('~/lib/utils/axios_utils').default;

axios.isMock = true;

// Fail tests for unmocked requests
axios.defaults.adapter = config => {
  const message =
    `Unexpected unmocked request: ${JSON.stringify(config, null, 2)}\n` +
    'Consider using the `axios-mock-adapter` module in tests.';
  const error = new Error(message);
  error.config = config;
  global.fail(error);
  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;