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

作者: tww844475003 分类: 前端开发 发布时间: 2022-03-03 23:01

安装 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')
  })
})
前端开发那点事
微信公众号搜索“前端开发那点事”

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注