axios-mock-adapter:axios的模擬調試器

最近學習vue,須要後臺模擬數據,從npm中搜索到axios-mock-adapter,即axios的模擬調試器,經過axios模擬調用後臺,後臺數據能夠使用mock.js來造假數據。現將研究的作以下記錄:
npm包連接vue

1.安裝

1.1 npm方式    
    npm install axios-mock-adapter --save-dev
1.2 script引入方式
<script src="https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.js"></script>
<script src="https://unpkg.com/axios-mock-adapter/dist/axios-mock-adapter.min.js"></script>

2.引入

2.1 es6  引入方式  import
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
2.2 require  引入方式
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

3.使用 example

首先建立一個實例
let mock = new MockAdapter(axios);ios

3.1模擬一個GET請求 ES6es6

//導入模塊
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
// 設置模擬調試器實例 
var mock = new MockAdapter(axios);
// 模擬任意GET請求到 /users 
//reply的參數爲 (status, data, headers) 
mock.onGet('/users').reply(200, {
  users: [
    { id: 1, name: 'John Smith' }
  ]
});
axios.get('/users')
  .then(function(response) {
    console.log(response.data);
  });

3.2 模擬一個GET請求帶參數的parametersnpm

mock.onGet('/users', { params: { searchText: 'John' } }).reply(200, {
  users: [
    { id: 1, name: 'John Smith' }
  ]
});
 
axios.get('/users', { params: { searchText: 'John' } } )
  .then(function(response) {
    console.log(response.data);
  });
//在初始化模擬調試器的時候,設置幾秒的延遲:響應的延遲 
var mock = new MockAdapter(axiosInstance, { delayResponse: 2000 });

3.3 傳遞一個function to replyaxios

mock.onGet('/users').reply(function(config) {
  //config是axios config 
  //返回一個數組[status, data, headers] 
  return [200, {
    users: [
      { id: 1, name: 'John Smith' }
    ]
  }];
});

3.4 沒有具體路徑的時候數組

// 拒絕全部的 POST 請求,返回 HTTP 500 
mock.onPost().reply(500);

3.5 模擬一個put請求 body/datapost

mock.onPut('/product', { id: 4, name: 'foo' }).reply(204);

4.實例

let mock = new MockAdapter(axios);
// 模擬成功請求
mock.onGet('/success').reply(200, {
  msg: 'success'
});
// 模擬錯誤請求
mock.onGet('/error').reply(500, {
  msg: 'failure'
});
//模擬登陸                POST
mock.onPost('/login').reply(config => {
  let {username, password} = JSON.parse(config.data);
  return new Promise((resolve, reject) => {
    let user = null;
    setTimeout(() => {
      let hasUser = LoginUsers.some(u => {
        if (u.username === username && u.password === password) {
          user = JSON.parse(JSON.stringify(u));
          user.password = undefined;
          return true;
        }
      });

      if (hasUser) {
        resolve([200, { code: 200, msg: '請求成功', user }]);
      } else {
        resolve([200, { code: 500, msg: '帳號或密碼錯誤' }]);
      }
    }, 1000);
  });
});
axios.post('/login', params).then(res => res.data);
//模擬批量刪除                           GET
mock.onGet('/user/batchremove').reply(config => {
  let { ids } = config.params;
  ids = ids.split(',');
 ***_Users = _Users.filter(u => !ids.includes(u.id));***
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([200, {
        code: 200,
        msg: '刪除成功'
      }]);
    }, 500);
  });
});
axios.get(`${base}/user/batchremove`, { params: params });
相關文章
相關標籤/搜索