Vue学习(5)使用单元测试

在组件开发的过程中,我们常使用单元测试来保证组件不会出问题,因此掌握必要的单元检测知识也很必要,在前面的构建Ant Design项目时,我们就选用了Jest来进行单元测试,下面就展示单元测试的一个小例子。

首先,我们写一个计数器----Counter.vue,点击"加1”按钮实现数字加1

<template>
    <div>
        count:{{count}}
        <button @click="handleClick">加1</button>
    </div>
</template>

<script>
    export default {
        name: "",
        data(){
            return{
                count:0
            }
        },
        methods:{
            handleClick(){
                this.count++;
            }
        }
    }
</script>

<style scoped>

</style>

然后在util/test下新建测试文件,名字必须为xxx.spec.js,我为了和组件名字统一,就取了Counter.spec.js,首先通过vue-test-utils提供的mount方法来挂载组件和我们要测试的Counter组件,如下

import { mount } from "@vue/test-utils";
import Count from "@/components/Counter.vue";

我们先生成快照,使用toMatchSnapshot,每一个测试都用it包裹,代码如下

describe("counterTest", () => {
  const wrapper = mount(Count);
  it("test", () => {
    expect(wrapper.html()).toMatchSnapshot();
  });
});

打开package.json,查看测命令,运行npm run test:unit即可生成快照。

然后我们想测试这个按钮点击后能否加1,方法是跟踪按钮点击后,count有无变成1,测试代码如下

describe("counterTest", () => {
  const wrapper = mount(Count);
  it("count++", () => {
    const button = wrapper.find("button");
    button.trigger("click");
    expect(wrapper.vm.count).toBe(1);
  });
});

如果显示passed,就表明测试成功

如果不想一遍遍的执行命令,可以使用npm run test:unit -- --watch,这样你修改测试代码后就会进行测试

我们还可以使用sinon来进行监听,使用npm i -save-dev sinon来下载安装,主要是监听有无change然后测试代码如下

import { mount } from "@vue/test-utils";
import Count from "@/components/Counter.vue";
import sinon from "sinon";
describe("counterTest", () => {
  const change = sinon.spy();
  const wrapper = mount(Count, {
    listeners: {
      change
    }
  });
  it("count++", () => {
    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);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章