• Chai的入门



    前言

    在部分企业级项目中,我们不免会在package.json文件中看到chai这个库,那么,

    一、chai是什么?

    Chai是一个BDD / TDD 断言库,适用于node和浏览器环境,可以与任何 javascript 测试框架完美搭配。

    • BDD(Behavior Driven Development 行为驱动开发)
    • TDD(Test-Driven Development 测试驱动开发)

    Chai有三种断言风格,分别是BDD的expect、should, 和TDD的assert;should不支持IE,在某些情况下还需要改变断言方式来填坑,所以建议使用expect,expect和should两者的语言链是相同的。

    二、安装命令

    1.通过npm安装

    npm install chai
    
    • 1

    2.引入语法

    import Chai, { expect } from 'chai';
    
    • 1

    三、expect的语法

    头部是expect方法;尾部是断言方法(比如equal、a/an、ok、match等);两者之间使用 to 或 to.be 连接。例如:expect(1).to.equal(1);

    1.类型判断

    a/an:判断数据类型,包括常见的数字、字符串、布尔值、对象、数组、函数及ES6新增的

    expect('foo').to.be.a('string');
    expect(false).to.be.a('boolean');
    expect(12).to.be.a('number');
    expect(null).to.be.a('null');
    expect(undefined).to.be.a('undefined');
    expect({}).to.be.a('object');
    expect([]).to.be.a('array');
    expect(Math.cos).to.be.a('function');
    expect(new Error).to.be.a('error');
    expect(/123/).to.be.a('regexp');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2.严格相等

    equal:基本类型的目标严格等于期望的值。
    eql:引用类型的目标严格等于期望的值,相当于 deep.equal 的简写,deep标记可以让其后的断言不是比较对象本身,而是递归比较对象的键值对

    expect(1).to.equal(1);
    expect('foo').to.equal('foo');
    expect(true).to.equal(true);
    expect(null).to.equal(null);
    expect(undefined).to.equal(undefined);
    expect({a: 1,b:{c:2}}).to.eql({a: 1,c:2});
    expect([1, 2]).to.deep.equal([1, 2]);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    3.否定

    not:跟在链式调用后面的否定断言

    // 这个函数没有异常
    expect(function () {}).to.not.throw();
    // 这个对象没有b属性
    expect({a: 1}).to.not.have.property('b');
    // 它是一个数组,里面里面不包含3
    expect([1, 2]).to.be.an('array').that.does.not.include(3);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    4.大于小于

    above:断言目标大于期望的值。
    least:断言目标大于等于期望的值。
    below:断言目标小于期望的值。
    most:断言目标小于等于期望的值。

    expect(50).to.be.above(12);
    expect([1, 2, 3]).to.have.length.above(2);
    
    • 1
    • 2

    5.包含

    include:用来判断是否包含某个内容。
    match:断言目标匹配到一个正则表达式。

    expect('foobar').to.include('foo');
    expect([1, 2, 3]).to.include(2);
    expect('foobar').to.match(/^foo/);
    expect({a: 1}).to.have.property('a');
    expect({a: 1, b: 2}).to.have.all.keys('a', 'b');
    expect({a: 1, b: 2}).to.have.any.keys('a');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    总结

    还有许多的没有写到,可以查看官方文档:chai

  • 相关阅读:
    C#编程学习
    Go sync.waitGroup
    【Qt】绘图与绘图设备
    【7.21-26】代码源 - 【体育节】【丹钓战】【最大权值划分】
    一文掌握深度学习实战——预测篇
    Wireshark CLI | Mergecap 篇
    真正牛的项目经理,都做到了这几点
    ae快捷键
    c++实现最大堆
    从金蝶云星空到赛意SMOM通过接口配置打通数据
  • 原文地址:https://blog.csdn.net/weixin_44887137/article/details/126410364