vue-cli 之 jest、@vue/test-utils 单元测试实践

安装 vue 项目

  • 安装脚手架
npm install -g @vue/cli
  • 创建项目
vue create vue-demo

安装步骤

用例1:renders 组件

// HelloWorld.vue
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

// helloWorld.spec.js
import { createLocalVue, mount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
  it('renders helloworld', () => {
    const msg = 'new message'
    const wrapper = mount(HelloWorld, {
      propsData: { msg }
    })
    expect(wrapper.text()).toMatch(msg)
  })
})

用例2:counter 组件 data 数据

// MyCounter.vue
<template>
  <div class="counter">
    <p>{{count}}</p>
    <el-button @click="addFn">ADD</el-button>
  </div>
</template>

<script>
export default {
  name: 'MyCounter',
  data () {
    return {
      count: 0
    }
  },
  methods: {
    addFn () {
      this.count++
    }
  }
}
</script>

// myCounter.spec.js
import { createLocalVue, mount } from '@vue/test-utils'
import HelloWorld from '@/components/MyCounter.vue'
import { Button } from 'element-ui'
const localVue = createLocalVue()
localVue.use(Button)

describe('MyCounter.vue', () => {
  it('add count', () => {
    const wrapper = mount(HelloWorld, { localVue })
    expect(wrapper.vm.count).toEqual(0)
    const btnClick = wrapper.find('button')
    btnClick.trigger('click')
    expect(wrapper.vm.count).toEqual(1)
  })
})

注意:这里由于 MyCounter.vue 组件,引用了第三方组件库 element-ui 库 button 按钮

import { createLocalVue, mount } from '@vue/test-utils'
import HelloWorld from '@/components/MyCounter.vue'
import { Button } from 'element-ui'
const localVue = createLocalVue()
localVue.use(Button)

const wrapper = mount(HelloWorld, { localVue })

如果没有 createLocalVue 就会报错

console.error
[Vue warn]: Unknown custom element: – did you register the component correctly? For recursive components, make sure to provide the “name” option.

运行结果

  • 输出用例报告配置
// package.json
{
  "jest": {
    "preset": "@vue/cli-plugin-unit-jest",
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.{js,vue}"
    ],
    "moduleFileExtensions": [
      "js",
      "jsx",
      "json",
      "vue"
    ]
  }
}

报告集合汇总类型

"coverageReporters": [
  "html",
  "text-summary"
]

实践示例

  • 示例1 【MyInput.vue】
// MyInput.vue
<template>
  <div>
    <el-input v-model="username"></el-input>
    <div
      v-if="error"
      class="error"
    >
      {{ error }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'MyInput',
  data () {
    return {
      username: ''
    }
  },
  computed: {
    error () {
      return this.username.trim().length < 7
        ? 'Please enter a longer username'
        : ''
    }
  }
}
</script>

// myInput.spec.js 风格一
import { shallowMount, createLocalVue } from '@vue/test-utils'
import MyInput from '@/components/MyInput.vue'
import { Input } from 'element-ui'
const localVue = createLocalVue()
localVue.use(Input)

describe('MyInput.vue', () => {
  it('input', async () => {
    const wrapper = shallowMount(MyInput, { localVue })
    await wrapper.setData({ username: ' '.repeat(7) })
    // exists 断言 Wrapper 或 WrapperArray 是否存在
    expect(wrapper.find('.error').exists()).toBe(true)
    await wrapper.setData({ username: 'www.ifrontend.net' })
    expect(wrapper.find('.error').exists()).toBe(false)
  })
})

// myInput.spec.js 风格二
import { shallowMount, createLocalVue } from '@vue/test-utils'
import MyInput from '@/components/MyInput.vue'
import { Input } from 'element-ui'
const localVue = createLocalVue()
localVue.use(Input)

const factory = (values = {}) => {
  return shallowMount(MyInput, {
    localVue,
    data() {
      return {
        ...values
      }
    }
  })
}

describe('MyInput.vue', () => {
  it('初始化', () => {
    const wrapper = factory()
    expect(wrapper.find('input').exists()).toBeFalsy()
  })
  it('输入7个空格', () => {
    const wrapper = factory({ username: ' '.repeat(7) })
    expect(wrapper.find('.error').exists()).toBeTruthy()
  })
  it('输入多余7位数的字符串', () => {
    const wrapper = factory({ username: 'www.ifrontend.net' })
    expect(wrapper.find('.error').exists()).toBeFalsy()
  })
})

  • 示例2 【MyCounter.vue】

测试辅助工具 sinon

spy生成一个间谍函数,它会记录下函数调用的参数,返回值,this的值,以及抛出的异常。
而spy一般有两种玩法,一种是生成一个新的匿名间谍函数,另外一种是对原有的函数进行封装并进行监听。

// MyCounter.vue
<template>
  <div class="counter">
    <p>{{count}}</p>
    <el-button @click="addFn">ADD</el-button>
  </div>
</template>

<script>
export default {
  name: 'MyCounter',
  data () {
    return {
      count: 0
    }
  },
  methods: {
    addFn () {
      this.count++
      this.$emit('change', this.count)
    }
  }
}
</script>

// myCounter.spec.js
import { createLocalVue, mount } from '@vue/test-utils'
import MyCounter from '@/components/MyCounter.vue'
import sinon from 'sinon'
import { Button } from 'element-ui'
const localVue = createLocalVue()
localVue.use(Button)

describe('MyCounter.vue', () => {
  const change = sinon.spy()
  const wrapper = mount(MyCounter, {
    localVue,
    listeners: {
      change
    }
  });
  it('渲染MyCounter组件', () => {
    expect(wrapper.html()).toMatchSnapshot()
  })
  it('add函数', () => {
    const button = wrapper.find('button')
    button.trigger('click')
    expect(wrapper.vm.count).toBe(1)
    expect(change.called).toBe(true)
    button.trigger('click')
    expect(change.callCount).toBe(2)
  })
})
  • 示例3 【MyChild.vue】 provide inject
// MyChild.vue
<template>
  <div class="my-child">
    MyChild:{{test}}
  </div>
</template>

<script>

export default {
  name: 'MyChild',
  inject: ['test']
}
</script>

// myChild.spec.js
import { shallowMount, config } from '@vue/test-utils'
import MyChild from '@/components/MyChild.vue'
config.provide.test = 'test provide value'

describe('MyChild.vue', () => {
  it('初始化', () => {
    const wrapper = shallowMount(MyChild)
    expect(wrapper.find('.my-child').text()).toContain('MyChild:test provide value')
  })
})
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伍哥的传说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值