美文网首页
vue-cli3 Jest

vue-cli3 Jest

作者: 带刀打天下 | 来源:发表于2019-10-11 10:28 被阅读0次
1. 创建项目
  • 使用vue-cli3创建项目,询问单元测试解决方案时选择Jest。详细步骤
  • 项目目录


    image.png
2. 使用
  • Counter.vue (在src/components/下创建该文件)
<template>
  <div>
    <div>{{ computedCount }}</div>
    <button @click="inc">加</button>
    <button @click="dec">减</button>
    <button @click="reset">重置</button>
  </div>
</template>

<script>
export default {
  props: {
    factor: { type: Number, default: 1 }
  },
  data() {
    return {
      count: 0
    };
  },
  methods: {
    inc() {
      this.count++;
    },
    dec() {
      this.count--;
    },
    reset() {
      this.count = 0;
    }
  },
  computed: {
    computedCount: function() {
      return this.count * this.factor;
    }
  }
};
</script>
  • Counter.spec.js (在tests/unit下创建该文件)
import { mount } from '@vue/test-utils'
import Counter from '@/components/Counter.vue'

describe("Counter.vue", () => {
    it("渲染Counter组件", () => {
        const wrapper = mount(Counter)
        expect(wrapper.element).toMatchSnapshot()
    })

    it("初始化之为0", () => {
        const wrapper = mount(Counter)
        expect(wrapper.vm.count).toEqual(0)
    })

    it("加1", () => {
        const wrapper = mount(Counter)
        wrapper.vm.inc()
        expect(wrapper.vm.count).toEqual(1)
    })

    it("减1", () => {
        const wrapper = mount(Counter)
        wrapper.vm.dec()
        expect(wrapper.vm.count).toEqual(-1)
    })

    it("重置", () => {
        const wrapper = mount(Counter)
        wrapper.vm.reset()
        expect(wrapper.vm.count).toEqual(0)
    })

    it("因数为10加1操作", () => {
        const wrapper = mount(Counter, { propsData: { factor: 10 } })
        wrapper.vm.inc()
        expect(wrapper.vm.computedCount).toEqual(10)
    })
})
3. 运行测试
  • Run your tests
npm run test
  • Lints and fixes files
npm run lint
  • Run your unit tests
npm run test:unit
4. 运行结果
image.png
参考:

相关文章

网友评论

      本文标题:vue-cli3 Jest

      本文链接:https://www.haomeiwen.com/subject/adctmctx.html