测试基础 [ES6] 基础和 anyproxy 中的使用示例

bauul · 2020年05月25日 · 1406 次阅读

var,let,const

// var的问题
1. var 声明的变量往往会越域
2. var可以声明多次
3. var 会变量提升

// let
1. let 声明的变量有严格局部作用域
2. let 只能声明一次
3. let 不存在变量提升
4. let 声明时需要初始化

// const
1. 声明后不允许改变

解构表达式

//数组解构
let arr = [1,2,3];
let a = arr[0];
let b = arr[1];
let c = arr[2];

// 解构写法
let [a,b,c] = arr;

// 对象解构
const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }
const { name: abc, age, language } = person;

// 声明对象简写
        const age = 23
        const name = "张三"
        const person1 = { age: age, name: name }

        const person2 = { age, name }
        console.log(person2);

字符串扩展

let str = "hello.vue";
console.log(str.startsWith("hello"));//true
console.log(str.endsWith(".vue"));//true
console.log(str.includes("e"));//true
console.log(str.includes("hello"));//true

字符串模板

let ss = `<div>
                    <span>hello world<span>
                </div>`;
        console.log(ss);

字符串插入变量和表达式

function fun() {
            return "这是一个函数"
        }

let info = `我是${abc},今年${age + 10}了, 我想说: ${fun()}`;
console.log(info);

函数优化

// 函数默认值
        function add2(a, b = 1) {
            return a + b;
        }
        console.log(add2(20));

// 不定参数
        function fun(...values) {
            console.log(values.length)
        }
        fun(1, 2)      //2
        fun(1, 2, 3, 4)  //4

// 箭头函数,箭头函数this不能使用,对象.属性
// 例
let print = obj => console.log(obj);
        print("hello");

// 例
let sum2 = (a, b) => a + b;
        console.log(sum2(11, 12));

// 例
const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }
let hello2 = ({name}) => console.log("hello," +name);
        hello2(person);

对象优化

        const person = {
            name: "jack",
            age: 21,
            language: ['java', 'js', 'css']
        }

        console.log(Object.keys(person));//["name", "age", "language"]
        console.log(Object.values(person));//["jack", 21, Array(3)]
        console.log(Object.entries(person));//[Array(2), Array(2), Array(2)]

// 对象合并
        const target = { a: 1 };
        const source1 = { b: 2 };
        const source2 = { c: 3 };

        //{a:1,b:2,c:3}
        Object.assign(target, source1, source2);

// 对象的函数属性简写
        let person3 = {
            name: "jack",
            // 以前:
            eat: function (food) {
                console.log(this.name + "在吃" + food);
            },
            //箭头函数this不能使用,对象.属性
            eat2: food => console.log(person3.name + "在吃" + food),
            eat3(food) {
                console.log(this.name + "在吃" + food);
            }
        }

// 对象深拷贝
        let p1 = { name: "Amy", age: 15 }
        let someone = { ...p1 }
        console.log(someone)  //{name: "Amy", age: 15}

// 合并对象
        let age1 = { age: 15 }
        let name1 = { name: "Amy" }
        let p2 = {name:"zhangsan"}
        p2 = { ...age1, ...name1 } 
        console.log(p2)

数组新增 map, reduce

//数组中新增了map和reduce方法。
        //map():接收一个函数,将原数组中的所有元素用这个函数处理后放入新数组返回。
         let arr = ['1', '20', '-5', '3'];
arr = arr.map(item=> item*2);


        //reduce() 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,
        //[2, 40, -10, 6]
        //arr.reduce(callback,[initialValue])
        /**
        1,2,3,4 分别表示参数的位置
         1、previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
    2、currentValue (数组中当前被处理的元素)
    3、index (当前元素在数组中的索引)
    4、array (调用 reduce 的数组)*/
        let result = arr.reduce((a,b)=>{
            console.log("上一次处理后:"+a);
            console.log("当前正在处理:"+b);
            return a + b;
        },100);
        console.log(result)

promise 异步操作

function get(url, data) {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            data: data,
            success: function (data) {
                resolve(data);
            },
            error: function (err) {
                reject(err)
            }
        })
    });
}

get("mock/user.json")
    .then((data) => {
        console.log("用户查询成功~~~:", data)
        return get(`mock/user_corse_${data.id}.json`);
    })
    .then((data) => {
        console.log("课程查询成功~~~:", data)
        return get(`mock/corse_score_${data.id}.json`);
    })
    .then((data)=>{
        console.log("课程成绩查询成功~~~:", data)
    })
    .catch((err)=>{
        console.log("出现异常",err)
    });

模块化

在 anyproxy 中,尝试过滤请求数据,生成指定对象

const request = require('request');

const testRecordURL = 'https://testx.com';
const preRecordURL = 'https://prex.com';
const prdRecordURL = 'https://prodx.com';

module.exports = {

  *beforeDealHttpsRequest(requestDetail) {
    return true;
  },
  *beforeSendRequest(requestDetail) {
    if (requestDetail.requestOptions.method === 'GET') {
      if (requestDetail.url.indexOf(testRecordURL) === 0 ||
          requestDetail.url.indexOf(preRecordURL) === 0 ||
          requestDetail.url.indexOf(prdRecordURL) === 0) {
        const apiTestCase = {};
        apiTestCase.url = {};
        apiTestCase.caseInfo = {};
        apiTestCase.method = 'GET';
        apiTestCase.caseInfo.caseOwner = 'record';
        apiTestCase.caseInfo.caseComment = 'record by proxy tool';
        apiTestCase.contentType = {};
        apiTestCase.asserts = {};
        apiTestCase.asserts.responseCode = 200;
        apiTestCase.requestHeader = {};
        apiTestCase.requestParameter = {};

        if (requestDetail.url.indexOf(testRecordURL) === 0) {
          apiTestCase.url.baseUrl = testRecordURL;
          apiTestCase.caseInfo.caseName = 'test--';
        } else if (requestDetail.url.indexOf(preRecordURL) === 0) {
          apiTestCase.url.baseUrl = preRecordURL;
          apiTestCase.caseInfo.caseName = 'pre--';
        } else if (requestDetail.url.indexOf(prdRecordURL) === 0) {
          apiTestCase.url.baseUrl = prdRecordURL;
          apiTestCase.caseInfo.caseName = 'prd--';
        }

        if (requestDetail.requestOptions.path.indexOf('?') > 0) {
          const tempPath = requestDetail.requestOptions.path;
          apiTestCase.url.apiUrl = tempPath.substr(0, tempPath.indexOf('?'));
          apiTestCase.caseInfo.caseName += apiTestCase.url.apiUrl;

          const bodyArray = tempPath.substr(tempPath.indexOf('?') + 1).split('&');
          console.log('bodyArray', bodyArray);
          apiTestCase.requestParameter.reqBody = {};
          for (let i = 0; i < bodyArray.length; i++) {
            const attr = bodyArray[i].split('=');
            apiTestCase.requestParameter.reqBody[attr[0]] = attr[1];
          }
        } else {
          apiTestCase.caseInfo.caseName += requestDetail.requestOptions.path;
          apiTestCase.url.apiUrl = requestDetail.requestOptions.path;
          if (typeof (requestDetail.requestData) !== 'undefined') {
            if (Buffer.isBuffer(requestDetail.requestData)) {
              const tempReqBody = requestDetail.requestData.toString();
              if (tempReqBody === '') {
                apiTestCase.requestParameter.reqBody = {};
              } else {
                apiTestCase.requestParameter.reqBody = { buffer: 'error record' };
              }
            } else {
              apiTestCase.requestParameter.reqBody = requestDetail.requestData;
            }
          }
        }

    for (const key in requestDetail.requestOptions.headers) {
          if (key.toLocaleLowerCase() === 'accept-encoding') {
            delete (requestDetail.requestOptions.headers[key]);
          }
        }
        apiTestCase.requestHeader.headerMap = requestDetail.requestOptions.headers;

        if (typeof (requestDetail.requestOptions.headers['Content-Type']) !== 'undefined') {
          const jsonReg = new RegExp(/json/, 'i');
          const formReg = new RegExp(/form/, 'i');
          const multiFormReg = new RegExp(/multipart/, 'i');
          if (jsonReg.test(requestDetail.requestOptions.headers['Content-Type'])) {
            apiTestCase.contentType.request = 'json';
          } else if (multiFormReg.test(requestDetail.requestOptions.headers['Content-Type'])) {
            apiTestCase.contentType.request = 'multiForm';
          } else if (formReg.test(requestDetail.requestOptions.headers['Content-Type'])) {
            apiTestCase.contentType.request = 'form';
          }
        }

        console.log('apiTestCase', apiTestCase);

        request({
          url: 'http://qa.gegejia.com/apitest/autotestserver/saverecordrequest',
          method: 'POST',
          json: true,
          headers: {
            'content-type': 'application/json',
          },
          body: apiTestCase
        });

        return requestDetail;
      }
    }
  }
};
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册