github: https://github.com/nuysoft/Mock/tree/refactoring87
宗旨: 无需等待,让前端独立于后端进行开发
简介: Mock.js is a simulation data generator to help the front-end to develop and prototype separate from the back-end progress and reduce some monotony particularly while writing automated tests.
适合
初学者: 如果你是一个刚刚开始写小程序的学习者,又苦于没有api拿来用,那么mock可以帮助你快速建立模拟数据,用于学习
开发者: 如果你的公司或者组织正在开发小程序,可是后台还没有能够提供给你调用接口,但是数据格式已经确定好,那么求人不如求己,自己先通过mock来模拟相关接口数据,先行一步。
开发使用
1.引入mock.js
在上面的github下下载mock.js
https://github.com/nuysoft/Mock/blob/refactoring/dist/mock.js
- (function webpackUniversalModuleDefinition(root, factory) {
- if(typeof exports === 'object' && typeof module === 'object')
- module.exports = factory();
- else if(typeof define === 'function' && define.amd)
- define([], factory);
- else if(typeof exports === 'object')
- exports["Mock"] = factory();
- else
- root["Mock"] = factory();
- })(this, function() {
- return /******/ (function(modules) { // webpackBootstrap
- /******/ // The module cache
- /******/ var installedModules = {};
- /******/ // The require function
- /******/ function __webpack_require__(moduleId) {
- /******/ // Check if module is in cache
- /******/ if(installedModules[moduleId])
- /******/ return installedModules[moduleId].exports;
建立统一的网络接口 我们建立一个DEBUG来标志是否使用模拟数据
- let API_HOST = "https://xxx.com/xxx";
- let DEBUG = true;
- var Mock = require('mocks.js')
- function ajax(data = '', fn, method = "get", header = {}) {
- if (!DEBUG) {
- wx.request({
- url: config.API_HOST + data,
- method: method ? method : 'get',
- data: {},
- header: header ? header : { "Content-Type": "application/json" },
- success: function (res) {
- fn(res);
- }
- });
- } else {
- // 模拟数据
- var res = Mock.mock({
- // 属性 list 的值是一个数组,其中含有 1 到 10 个元素
- 'list|1-10': [{
- // 属性 id 是一个自增数,起始值为 1,每次增 1
- 'id|+1': 1
- }]
- })
- // 输出结果
- console.log(JSON.stringify(res, null, 4))
- fn(res);
- }
- }
- module.exports = {
- ajax: ajax
- }
调用使用
- //index.js
- //获取应用实例
- var app = getApp()
- var API = require('../../utils/api.js')
- Page({
- data: {
- },
- onLoad: function () {
- console.log('onLoad')
- var that = this
- // 使用 Mock
- API.ajax('',function(res){
- //这里既可以获取模拟的res
- });
- }
- })
发布模式 为了保证我们程序的最小化,发布模式下我们需要删除mock.js,并更改DEBUG为false,或者彻底删除api.js中的else部分
代办 由于mock.js中有对window等的封装,文件比较大,目前可能只能使用简单数据