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

  1. import axios from './lib/utils/axios_utils';
  2. axios.get(url)
  3. .then((response) => {
  4. // `data` is the response that was provided by the server
  5. const data = response.data;
  6. // `headers` the headers that the server responded with
  7. // All header names are lower cased
  8. const paginationData = response.headers;
  9. })
  10. .catch(() => {
  11. //handle the error
  12. });

Mock Axios response in tests

为了帮助我们模拟响应,我们使用axios-mock-adapter .

spyOn()优势:

  • 无需创建响应对象
  • 不允许通话(我们要避免)
  • 简单的 API 来测试错误情况
  • 提供replyOnce()以允许不同的响应

我们还决定不使用Axios 拦截器,因为它们不适合模拟.

Example

  1. import axios from '~/lib/utils/axios_utils';
  2. import MockAdapter from 'axios-mock-adapter';
  3. let mock;
  4. beforeEach(() => {
  5. // This sets the mock adapter on the default instance
  6. mock = new MockAdapter(axios);
  7. // Mock any GET request to /users
  8. // arguments for reply are (status, data, headers)
  9. mock.onGet('/users').reply(200, {
  10. users: [
  11. { id: 1, name: 'John Smith' }
  12. ]
  13. });
  14. });
  15. afterEach(() => {
  16. mock.restore();
  17. });

Mock poll requests in tests with Axios

因为轮询功能需要一个标头对象,所以我们需要始终包含一个对象作为第三个参数:

  1. mock.onGet('/users').reply(200, { foo: 'bar' }, {});