2019-08-11 | 前端技术分享 | UNLOCK

论作假,我是认真滴😄---Mock详解

在做程序开发的时候,我们经常会用到一些测试数据,相信大多数同学是这么来造测试数据的:

test1
test01
test02
测试1
测试2
测试数据1
这是一段测试文本
这是一段很长很长很长的测试文本...

中枪的请举手。

不仅要自己手动敲这些测试数据,还敲的这么假。那有啥办法呢?难不成有什么东西能自动给我造点以假乱真的数据啊?你别说,还真有!

在 JavaScript 中有个神库,叫做 Mock,(Python中的叫做Faker,还是Python造假库的名字起的接地气呀O(∩_∩)O)可以自动帮我们来生成各种各样的看起来很真的”假“数据,让我们来看看吧!

一、为什么要伪造数据

要点提示:

  • Python - Faker
  • JavaScript - Mock.js
  • 场景举例:
    • 一般数据伪造 : 贴吧评论、影评、表单验证等
    • 特定场合数据伪造 : 数学场景(微积分验证等)、机场信息(前后端一个人编写,直接调用接口)、游戏(王者荣耀、吃鸡<测试工作的介绍—吐槽大会>)

二、Mockjs 详解

要点提示 :

  • 安装
    • 通过require引入的方式
    • 通过script标签引入本地下载好的mockjs文件或者使用cdn
  • 语法
    重点讲解:
    • Mock.Random()<Image、Web、扩展方法讲解 >(如何生成图片的网络地址、顶级域名)

我会通过官方文档来给各位介绍这个库。具体的语法讲解请参照官方文档,这里不再赘述。

Talk is cheap,show you my code(请看测试代码)

var Mock = require('mockjs');
var obj = {a:'AAA',b:"BBB",c:"CCC",d:"DDD",e:"EEE"};
var arr = ["a","b","c","d","e","f"];
var data = Mock.mock({
    /*"str|1-3":"abc",//随机重复多少次
    "str|2":"abc",//固定重复多少次
    "arr|1-3":[
        {
            "id|+1":5
        }
    ],
    //声明生成的数据类型
    "num|2-4":2,
    //生成小数
    "num|2-4.1-3":2,
    //布尔值
    "bool|1":true, //随机生成true or false
    "bool2|1-5":false,
    //对象
    "obj|2":obj,
    "obj2|1-3":obj,
    //数组
    "arr|1":arr,
    "arr21|+2":arr,
    "arr22|+2":arr,
    "arr23|+1":arr,
    "arr3|1-3":arr,
    "arr4|2":arr,
    "arr5|1-3":[
        {
            "id|+10":1,
            "name|1-3":"abc"
        }
    ],
    */ 
    /*
     "fun":function () {
            //函数  给啥返回啥
            return Mock.mock({
                "a|1-3":"AAA"
            });
        },
        //占位符
        name: {
            first: '@FIRST',
            middle: '@FIRST',
            last: '@LAST',
            full: '@first @middle @last'
        }
        */
});
console.log(JSON.stringify(data, null, 4));

参数解释 :
JSON.stringify

var Mock = require('mockjs');
var arr = ["a","b","c","d","e"]
var Random = Mock.Random;
//自定义扩展方法
Random.extend({
    constellation: function(date) {
        var constellations = ['白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座', '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座']
        return this.pick(constellations)
    },
    sum:function (num1,num2) {
        return num1+num2
    }
})
/*
var Random = Mock.Random;
console.log(Random.email())
console.log(Mock.mock("邮箱:@email"));
*/
var data = Mock.mock({
    /*
    "bool":"@BOOLEAN",
    "bool|2":"@BOOLEAN(1,3,false)",
    "bool3|1-3":false,
    "natural":"@NATURAL",
    "natural1":"@NATURAL(-100,100)",

    "interger":"@INTERGER",
    "interger1":"@INTERGER(0,100)",
    "num":"@INTERGER(1,10)",

    "float":"@FLOAT",
    "float2":"@FLOAT(0,100,1,3)",
    "float3|0-100.1-3":1,
    "price":"@FLOAT(1,100,1,2)",
    //计算总价格
    "total":function(){
        return this.price*this.num
    },
    //特殊字符
    "char1":"@CHARACTER",
    "char2":"@CHARACTER('shipudong')",//随机生成一个
    "char3":"@CHARACTER('upper')",

    //字符串
    "str":"@STRING",
    "str1":"@STRING('number',5)", //生成5个数字
    "str2":"@STRING('number',1,4)", //生成1-4个数字

    //随机生成一个数组   range
    "range":"@RANGE(1,10,2)"

    // 随机生成一个日期
    "date":"@DATE('yyyy-MM-dd')",
    "time":"@TIME()",
    "time1":"@TIME(H:m:s)",
    "datetime":"DATETIME(yyyy-MM-dd H:m:s)"

    //返回当前时间
    "now":"NOW",
    "now1":"NOW(yyyy-MM-dd H:m:s)"
    "now2":"NOW('day','yyyy-MM-dd H:m:s')",

    //图片
    //对中文不友好
    "img":"@IMG('300*100','#F00','#00F','jpg','shipudong is so handsome')"
    //浏览器查看图片格式

    //base64
    "dataimg":"DATAIMAGE('300*100'.'石璞东好帅')"

    //颜色

    "color":"@COLOR",
    "hex":"@HEX",
    "rgb":"@RGB",
    "rgba":"@RGBA",
    "hsl":"@HSL"
    //文本
    "paragraph":"@PARAGRAPH",
    "paragraph2":"@PARAGRAPH(2)",
    "paragraph3":"@PARAGRAPH(1,3)",

    "cparagraph":"@CPARAGRAPH",
    "cparagraph2":"@CPARAGRAPH(2)",
    "cparagraph3":"@CPARAGRAPH(1,3)",

    "sentence":"@SENTENCE",
    "sentence2":"@SENTENCE(2)",
    "sentence3":"@SENTENCE(1,6)",

    "csentence":"@CSENTENCE",
    "csentence2":"@CSENTENCE(3)",
    "csentence3":"@CSENTENCE(1,6)",

    "word":"@WORD",
    "word2":"@WORD(3)",
    "word3":"@WORD(2,6)",

    "cword":"@CWORD",
    "cword2":"@CWORD(3)",
    "cword3":"@CWORD(2,6)",

    "title1":"@TITLE",
    "title2":"@TITLE(3)",
    "title3":"@TITLE(1,6)",

    "ctitle":"@CTITLE",
    "ctitle2":"@CTITLE(3)",
    "ctitle3":"@CTITLE(1,6)",

    "first":"@FIRST",
    "last":"@LAST",
    "name":"@NAME",
    "name1":"@NAME(true)",

    "cfirst":"@CFIRST",
    "clast":"@CLAST",
    "cname":"@CNAME",
    "cname1":"@CNAME(true)",

    "url1":"@URL",
    "url2":"@URL('http')",
    "url":"@URL('http','www.shipudong.com')",

    "protocol":"@PROTOCOL",

    'domain':"@DOMAIN('com')",

    "tld":"TLD",

    "email":"@EMAIL",
    "email2":"@EMAIL('163.com')",
    "email3":/\d{6,9}@qq\.com/,

    "ip":"@IP",

    "region":"@REGION",
    "province":"@PROVINCE",

    "city":"@CITY",
    "city2":"@CITY(true)",

    "country":"COUNTRY",
    "country2":"COUNTRY(true)"

    "zip":"@ZIP",

    "capitalize":"@CAPITALIZE('hELlo world!')",
    "upper":"@UPPER('hELlo world!')",
    "lower":"@LOWER('hELlo world!')",

    "pick":"@PICK(arr)",
    "shuffle":"@SHUFFLE(arr)",

    "guid":"@GUID",
    "id":"@ID",
    "inc":"@INCREMENT(2)",
    "inc2":"@INCREMENT",
    "inc3":"@INCREMENT",
*/
    "constellation":"@CONSTELLATION",
    sum:"@SUM(6,4)"
})
console.log(JSON.stringify(data, null, 4));

三、ajax数据拦截

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<button id ="btn">点我啊</button>

<script src="https://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script>
<script src="mock-min.js"></script>
<script>
    // ajax数据拦截
    Mock.mock('a.json',{
       "str|1-3":"shipudong",
        "id|+1":1,
        "title":"@CTITLE",
        "name":"@CNAME"
    });

    $(function () {
        $('#btn').click(function () {
            $.get('a.json',function (res) {
                console.log(res);
            })
        })
    })
</script>
</body>
</html>

评论加载中