Axios
原文:https://docs.gitlab.com/ee/development/fe_guide/axios.html
Axios
我们使用Axios在 Vue 应用程序和大多数新代码中与服务器进行通信.
为了确保设置了所有默认值,您不应直接使用 Axios ,而应从axios_utils导入 Axios.
CSRF token
我们所有的请求都需要 CSRF 令牌. 为了确保设置此令牌,我们将导入Axios ,设置令牌并导出axios .
应该使用此导出模块,而不是直接使用 Axios 以确保已设置令牌.
Usage
 import axios from './lib/utils/axios_utils';
  axios.get(url)
    .then((response) => {
      // `data` is the response that was provided by the server
      const data = response.data;
      // `headers` the headers that the server responded with
      // All header names are lower cased
      const paginationData = response.headers;
    })
    .catch(() => {
      //handle the error
    }); 
Mock Axios response in tests
为了帮助我们模拟响应,我们使用axios-mock-adapter .
比spyOn()优势:
- 无需创建响应对象
 - 不允许通话(我们要避免)
 - 简单的 API 来测试错误情况
 - 提供
replyOnce()以允许不同的响应 
我们还决定不使用Axios 拦截器,因为它们不适合模拟.
Example
 import axios from '~/lib/utils/axios_utils';
  import MockAdapter from 'axios-mock-adapter';
  let mock;
  beforeEach(() => {
    // This sets the mock adapter on the default instance
    mock = new MockAdapter(axios);
    // Mock any GET request to /users
    // arguments for reply are (status, data, headers)
    mock.onGet('/users').reply(200, {
      users: [
        { id: 1, name: 'John Smith' }
      ]
    });
  });
  afterEach(() => {
    mock.restore();
  }); 
Mock poll requests in tests with Axios
因为轮询功能需要一个标头对象,所以我们需要始终包含一个对象作为第三个参数:
 mock.onGet('/users').reply(200, { foo: 'bar' }, {});