美文网首页
前端自动化测试Jest的学习日记(二)

前端自动化测试Jest的学习日记(二)

作者: 带熊二来看简书 | 来源:发表于2020-02-25 20:34 被阅读0次

    什么是 Jest


    Jest是 Facebook 的一套开源的 JavaScript 测试框架, 它自动集成了断言、JSDom、覆盖率报告等开发者所需要的所有测试工具,是一款几乎零配置的测试框架。

    Jest原理说明


    index.js中

    function add(a,b){
        return a + b;
    }
    function reduce(a,b){
        return a - b;
    }
    module.exports={
        add,reduce
    }
    

    index.jest.js中

    //简单
    /*
    const {add,reduce} =require("./index.js")
    var result = add(1,2);
    var m=3;
    if(result == m){
        console.log('测试通过')
    }else{
        throw new Error('1+2的结果不等于'+m);
    }
    */
    //封装
    /*
    function expect(result){
        return {
            toBe(actual){
                if(result !== actual){
                    throw new Error('预期值与测试值不符')
                }
            }
        }
    }
    expect(reduce(3,1)).toBe(2);
    expect(reduce(1,2)).toBe(3);
    */
    //再次封装
    function expect(result){
        return {
            toBe(actual){
                if(result !== actual){
                    throw new Error('预期值与测试值不符')
                }
            }
        }
    }
    function test(des,calllback){
        try{
            callback();
            console.log(`${des}通过测试`)
        }catch(e){
            console.log(`${des}没有通过测试:${e}`)
        }
    }
    test("测试add函数",()=>{
        expect(add(1,2)).toBe(3);
    })
    test("测试reduce函数",()=>{
        expect(add(5,2)).toBe(3);
    })
    

    Jest的安装


    1.新建项目文件夹
    2.初始化项目npm init -y
    3.安装jestnpm install jest -D
    3.jest本身不支持ES6的语法,需要安装babel
    npm install babel-jest babel-core babel-preset-env regenerator-runtime
    4.新建.babelrc文件

    {
      "presets": ["env"]
    }
    

    5.修改package.json中的test脚本

    "scripts": {
      "test": "jest"
    }
    

    相关文章

      网友评论

          本文标题:前端自动化测试Jest的学习日记(二)

          本文链接:https://www.haomeiwen.com/subject/mtxxchtx.html