chai.js单元测试

chai.js 单元测试 BDD/TDD assert库

chai.js有三种语法,我们使用expect,常用写法:

var expect = chai.expect;

expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.eq('bar') //上一行简写
expect(foo).to.have.lengthOf(3);
expect(tea).to.have.property('flavors').with.lengthOf(3);

比较两个对象:

expect([1,2]).to.eq([1,2])  //false,因为是不同地址的两个对象
expect([1,2]).to.deep.eq([1,2])  //true,比较内容

具体用例:

import chai from 'chai'

{
    const Constructor = Vue.extend(Button);
    const button = new Constructor({
        propsData: {
            icon: 'settings'
        }
    });
    button.$mount();
    let useElement = button.$el.querySelector('use');
    console.log(useElement);
    expect(useElement.getAttribute('xlink:href')).to.eq('#i-settings');
    button.$el.remove();
    button.$destroy()
}
{
    const Constructor = Vue.extend(Button);
    const button = new Constructor({
        propsData: {
            icon: 'settings',
            loading:true
        }
    });
    button.$mount();
    let useElement = button.$el.querySelector('use');
    console.log(useElement);
    expect(useElement.getAttribute('xlink:href')).to.eq('#i-loading');
    button.$el.remove();
    button.$destroy()
}
{
    const div=document.createElement('div');
    document.body.appendChild(div);
    const Constructor = Vue.extend(Button);
    const button = new Constructor({
        propsData: {
            icon: 'settings',
            iconPosition:'right'
        }
    });
    button.$mount(div);
    let svg = button.$el.querySelector('svg');
    let order = window.getComputedStyle(svg).order;
    expect(order).to.eq(`2`);
    button.$el.remove();
    button.$destroy()
}

chai.spy

import spies from 'chai-spies'
const expect = chai.expect;
chai.use(spies);
{
    const Constructor = Vue.extend(Button);
    const vm = new Constructor({
        propsData: {
            icon: 'settings'
        }
    });
    vm.$mount();
//chai.spy这个回调才能知道它是否被调用
    let spy = chai.spy(function () {});
    vm.$on('click',spy);
    let button = vm.$el;;
    button.click();
//断言click时这个回调被调用了
    expect(spy).to.have.been.called();
    vm.$el.remove();
    vm.$destroy()
}

你可能感兴趣的:(chai.js单元测试)