Vue前端自动化测试-Vue Test Utils

Vue Test Utils简介

vue-test-utils是vue官方的单元测试框架,提供了一系列非常方便的工具,使我们更轻松地为vue构建的应用来编写单元测试。主流的JavaScript测试运行器有很多,但vue-test-utils都能支持。它是与测试运行器无关的。

环境配置

通过脚手架 vue-cli 来新建项目的时候,如果选择了 Unit Testing 单元测试且选择的是 Jest 作为测试运行器,那么在项目创建好后,就会自动配置好单元测试需要的环境。本文主要讲的就是新建项目之初没有选择单元测试功能,需要后面去添加的配置。

npm i @vue/cli-plugin-unit-jest -D
npm i @vue/test-utils -D
v3:npm i @vue/vue3-jest@^27.0.0-alpha.1 -D
v2:npm i @vue/vue2-jest@^27.0.0-alpha.2 -D

配置Jest

项目根目录创建jest.config.js文件

module.exports = {
  //有啥需要就在这里配置...
  preset: "@vue/cli-plugin-unit-jest",
};

配置package.json

  "scripts": {
    "test": "vue-cli-service test:unit",
  },

编写测试文件

项目根目录创建tests/unit/example.spec.js文件

import { shallowMount } from "@vue/test-utils";
import HelloWorld from "@/components/HelloWorld.vue";

describe("HelloWorld.vue", () => {
  it("renders props.msg when passed", () => {
    const msg = "new message";
    const wrapper = shallowMount(HelloWorld, {
      props: { msg },
    });
    expect(wrapper.text()).toMatch(msg);
  });
});

HelloWorld.vue文件 

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

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

<style scoped>

</style>

  • shallowMount 将会创建一个包含被挂载和渲染的 Vue 组件的 Wrapper,只存根当前组件,不包含子组件。
  • describe(name, fn) 这边是定义一个测试套件,HelloWorld.vue 是测试套件的名字,fn 是具体的可执行的函数
  • it(name, fn) 是一个测试用例,输入框初始值为空字符串 是测试用例的名字,fn 是具体的可执行函数;一个测试套件里可以保护多个测试用例。
  • expect 是 Jest 内置的断言风格,业界还存在别的断言风格比如 Should、Assert 等。
  • toBe 是 Jest 提供的断言方法,比如expect(1+1).toBe(2),更多的可以到Jest Expect 查看具体用法。

执行测试命令

npm run test

猜你喜欢

转载自blog.csdn.net/qq_55172460/article/details/129723692
今日推荐