Chai.js

让断言更加方便 https://www.chaijs.com/

  1. chai.should();
  2. foo.should.be.a('string');
  3. foo.should.equal('bar');
  4. foo.should.have.lengthOf(3);
  5. tea.should.have.property('flavors')
  6. .with.lengthOf(3);
  1. var assert = chai.assert;
  2. assert.typeOf(foo, 'string');
  3. assert.equal(foo, 'bar');
  4. assert.lengthOf(foo, 3)
  5. assert.property(tea, 'flavors');
  6. assert.lengthOf(tea.flavors, 3);
  1. var expect = chai.expect;
  2. expect(foo).to.be.a('string');
  3. expect(foo).to.equal('bar');
  4. expect(foo).to.have.lengthOf(3);
  5. expect(tea).to.have.property('flavors')
  6. .with.lengthOf(3);

安装

  1. $ npm install chai -D

目录结构

在项目的根目录创建 test 文件夹
创建文件 button.test.js

  1. const expect = chai.expect;
  2. import Vue from 'vue'
  3. import Button from '../src/button'
  4. Vue.config.productionTip = false
  5. Vue.config.devtools = false

最简单的例子

Constructor是一个函数,通过Constructor构造一个button实例
image.png
image.png

  1. describe('Button', () => {
  2. it('存在.', () => {
  3. expect(Button).to.exist
  4. })
  5. })
  1. it('可以设置icon.', () => {
  2. const Constructor = Vue.extend(Button)
  3. const vm = new Constructor({
  4. propsData: {
  5. icon: 'settings'
  6. }
  7. }).$mount()
  8. const useElement = vm.$el.querySelector('use')
  9. expect(useElement.getAttribute('xlink:href')).to.equal('#isettings')
  10. vm.$destroy()
  11. })

模拟事件触发

安装 chai-spies

  1. yarn add -D chai-spies
  1. it('点击 button 触发 click 事件', () => {
  2. const Constructor = Vue.extend(Button)
  3. const vm = new Constructor({
  4. propsData: {
  5. icon: 'settings',
  6. }
  7. }).$mount()
  8. const callback = sinon.fake();
  9. vm.$on('click', callback)
  10. vm.$el.click()
  11. expect(callback).to.have.been.called
  12. })