MockAjax - 用于接口数据模拟的插件


Apache-2.0
跨平台
JavaScript

软件简介

MockAjax 是用做接口数据模拟的插件,它是基于 XMLHttpRequestfetch,
因此没有框架限制,你可以用jQuery做http client,也可以用axios,也可以用fetch。同时 MockAjax
没有框架依赖,方便使用。

这个插件是对API接口平台的补充,可以任意定制自己的数据模拟,为了灵活模拟数据,你可以引入mockjs或者faker,来生成你想要的数据。

备注:目前支持status=200

背景

在后端接口还没开发完成的时候,前端经常需要自己做数据模拟,虽然市面上提供了easy-mock,或者yapi这种接口模拟平台,但是有些时候这些平台是没法满足我们的定制需求的。例如:接口2的请求参数依赖于接口1模拟出来的数据。
市面上已经有的比较出名的是jquery-mockjax,但是它是基于jQuery的,并不适用于axios等其他的http client。因此需要有一个脱离于http
client的库来提供mock功能。

开始使用

引入mock库

<script src="/dist/mockajax.min.js"></script>

注意:这个库一定要ajax请求之前引用

编写mock规则

例如:

MockAjax.mock([
  {
    url: '/user/:id/:name',
    response: function(req) {
      return {
        name: req.params.name,
        id: req.params.id,
        age: req.query.age,
        country: req.query.country
      }
    }
  },
  {
    url: '/user/:name',
    response: function(req) {
      return {
        name: req.params.name,
        age: req.query.age,
        country: req.query.country
      }
    }
  },
  {
    url: '/user',
    method: 'POST',
    response: function(req) {
      return {
        name: req.body.firstName + req.body.lastName
      }
    }
  },
  {
    url: '/user',
    method: 'put',
    response: function(req) {
      return {
        name: req.body.firstName + req.body.lastName
      }
    }
  },
  {
    url: '/user/:id',
    method: 'delete',
    response: function(req) {
      return {
        id: req.params.id
      }
    }
  }
])

然后可以做任何的ajax请求了

axios.post('/user', {
  firstName: 'free',
  lastName: 'fish'
}).then((response) => {
  assert.equal(response.data.name, 'freefish')
}).catch(error => {
})