vue.js 全局应用js

by Mukul Khanna

由Mukul Khanna

如何在不到7分钟的时间内测试您的Vue.js应用 (How you can test your Vue.js apps in less than seven minutes)

Before we dive into the implementation, let’s get a few concepts cleared.

在深入研究实现之前,让我们先清除一些概念。

什么是测试? (What is testing?)

Manually trying all possible inputs to a basic form validator can be cumbersome.

手动尝试将所有可能的输入输入基本表单验证器可能很麻烦。

It might not seem like a big deal for a small website. But for bigger and more complex web applications consisting of dozens of components along with their functions, routes, states, mutations and so on, it is not feasible or advisable to test the functioning of all these constituents.

对于一个小型网站来说似乎并不重要。 但是对于包含数十个组件以及它们的功能,路由,状态,突变等的更大,更复杂的Web应用程序,测试所有这些组件的功能是不可行或不明智的。

Automating this part of the trial and error based assessments of the code we have written is known as testing or automated testing.

使我们编写的代码的基于反复试验的评估的这一部分自动化,称为测试自动化测试

Edd Yerburgh, a core Vue team member and the maintainer of vue-test-utils (formerly Avoriaz), defines automated testing in his book as:

Vue核心团队成员和vue-test-utils(以前称为Avoriaz )的维护者Edd Yerburgh在他的书中将自动化测试定义为:

Automated testing is the practice of writing programs to run tests against your application code. Once the programs are written, they can be executed automatically.

自动化测试是编写程序以针对您的应用程序代码运行测试的实践。 一旦编写了程序,就可以自动执行它们。

There are essentially three types of tests:

基本上有三种类型的测试:

  1. Unit tests单元测试
  2. End to end tests端到端测试
  3. Snapshot tests快照测试

单元测试 (Unit tests)

These are basic tests that check if the atomic elements of the website (Vue components and functions) work properly. Edd calls them component contracts. Each component is expected to work as it has promised to do, and these tests make sure that they are fulfilled.

这些是基本测试,用于检查网站的原子元素(Vue组件和功能)是否正常运行。 Edd称它们为组成合同 。 预计每个组件都可以像预期的那样工作,并且这些测试确保已实现它们。

端到端(E2E)测试 (End to end (E2E) tests)

E2E tests test the whole workflow of the website. It can be said that one E2E test is made up of multiple granular unit tests. They are slow, but they check the whole functionality of the website.

E2E测试可测试网站的整个工作流程。 可以说,一个端到端测试由多个粒度单元测试组成。 它们速度很慢,但是会检查网站的整体功能。

But they are also difficult to debug because it’s tough to locate which parts didn’t work as they were supposed to. There could be more than one reason that the tests failed.

但是,它们也很难调试,因为很难找到哪些零件无法正常工作。 测试失败的原因可能不止一个。

快照测试 (Snapshot tests)

Bugs in the code don’t only affect the functionality of the website, but also the positioning of the components in the UI. Snapshot tests check for such changes in the appearance of the application. It involves rendering the UI, capturing a screenshot, and comparing it to a reference image stored along with the test. The test fails if the two images don’t match.

代码中的错误不仅会影响网站的功能,还会影响UI中组件的位置。 快照测试检查应用程序外观中是否存在此类更改。 它涉及渲染UI,捕获屏幕截图,并将其与与测试一起存储的参考图像进行比较。 如果两个图像不匹配,则测试失败。

These tests also help developers write proper documentation of the code, which is quite useful in large scale applications with multiple contributors.

这些测试还有助于开发人员编写适当的代码文档,这在具有多个贡献者的大规模应用程序中非常有用。

So now that we’ve established that testing can help us save a lot of time and optimize our code, let’s see how tests are configured, created, and run.

因此,既然我们已经确定测试可以帮助我们节省大量时间并优化我们的代码,那么让我们看看如何配置,创建和运行测试。

We will be using vue-test-utils as the testing utility library for Vue.js. Now we also need to choose a test runner. There are many to choose from, but Jest and Mocha-Webpack are both equally good. They just have some tradeoffs between the configuration upfront and the support for SFCs (single file components).

我们将使用vue-test-utils作为Vue.js的测试实用程序库 现在我们还需要选择一个测试跑步者。 有很多选择,但是Jest和Mocha-Webpack都同样出色。 他们只是在预先配置和对SFC(单个文件组件)的支持之间进行了权衡。

We will be using the mocha-webpack configuration for this demo.

在本演示中,我们将使用mocha-webpack配置。

创建项目 (Creating the project)

npm install vue
npm install --global vue-cli
vue init webpack vue-testing
cd vue-testing
npm install
npm run dev

Using the above commands, create a Vue webpack project in which we will be setting up the testing environment.

使用以上命令,创建一个Vue Webpack项目,我们将在其中建立测试环境。

安装依赖 (Installing dependencies)

To install vue-test-utils, mocha, and mocha-webpack:

要安装vue-test-utils mocha, 和mocha-webpack:

npm install --save-dev @vue/test-utils
npm install --save-dev mocha mocha-webpack

To emulate a subset of a browser environment to run our tests, we’ll install jsdom and jsdom-global:

为了模拟浏览器环境的一部分来运行我们的测试,我们将安装jsdom 和jsdom-globa l:

npm install --save-dev jsdom jsdom-global

Some of the dependencies that we will be importing in our tests are difficult for the webpack to bundle. So, to be able to remove them from the bundling process and to increase test bootup speed, we install node-externals:

我们将在测试中导入的某些依赖项对于webpack来说很难捆绑。 因此,为了能够将它们从捆绑过程中删除并提高测试启动速度,我们安装了node-externals:

npm install --save-dev webpack-node-externals

Vue recommends expect as an assertion library that essentially decides whether the test fails or passes depending on the argument it receives.

Vue建议将Expect作为断言库,该库从本质上根据测试收到的参数来确定测试是否失败。

npm install --save-dev expect

We need to make it globally accessible to avoid importing it in every single test. We create a directory named test in the root directory and create a file named test/setup.js . Import the modules with require:

我们需要使其在全球范围内可访问,以避免在每个测试中都将其导入。 我们创建一个名为test的目录 在根目录中,创建一个名为test / setup.js的文件 使用require导入模块

//setup.js
require('jsdom-global')()
global.expect = require('expect')

We can also include code coverage in the test results using the istanbul plugin to get a report like this:

我们还可以使用伊斯坦布尔在测试结果中包括代码覆盖率 插入 得到这样的报告:

It is used to describe the degree to which the source code of an application is executed when a particular test suite runs.

它用于描述特定测试套件运行时应用程序源代码的执行程度。

npm install --save-dev nyc babel-plugin-istanbul

Also in the .babelrc in the plugins array, add istanbul:

同样在.babelrc中插件中 数组,添加伊斯坦布尔:

//.babelrc
plugins": ["transform-vue-jsx", "transform-runtime", "istanbul"]

So we have installed all the dependencies, and it’s time to make the final configurations before we can start writing the tests.

因此,我们已经安装了所有依赖项,是时候进行最终配置了,然后才能开始编写测试。

In package.json, we need to add a test script that runs the test:

package.json中 ,我们需要添加一个测试 运行测试的脚本:

//package.json
"scripts":{
"test": "cross-env NODE_ENV=test nyc mocha-webpack --webpack-config build/webpack.base.conf.js --require test/setup.js test/**/*.spec.js"
}

We also need to specify the files that needed to be included for the code coverage in the package.json:

我们还需要在package.json中指定代码覆盖所需包含的文件

//package.json
"nyc":{    "include":[      "src/**/*.(js|vue)" ],    "instrument":false,    "sourceMap":false}

The last configuration before writing the test would be adding the following in webpack.base.conf.js:

编写测试之前的最后一个配置是在webpack.base.conf.js中添加以下内容:

//webpack.base.conf.js
if (process.env.NODE_ENV === 'test'){  module.exports.externals = [require('webpack-node-externals')()]  module.exports.devtool = 'inline-cheap-module-source-map'}

We can perform our test on the inbuilt Vue component that comes with the webpack boilerplate.

我们可以对webpack样板随附的内置Vue组件执行测试。

Every test file would have a ‘.spec.js’ extension.

每个测试文件都有一个“ .spec.js” 延期。

In the test directory, we add a test file testOne.spec.js

在测试目录中,我们添加一个测试文件testOne.spec.js

//testOne.spec.js
import {shallow} from '@vue/test-utils'
import HelloWorld from '../src/components/HelloWorld.vue'

We start by importing shallow from the vue-test-utils. Shallow creates a wrapper for the Vue component on which we want to run the test. This wrapper is an object that contains the mounted component and methods to test parts of the code. Then we import the Vue component on which we run the test.

我们从进口浅水开始 来自vue-test-utils 为要在其上运行测试的Vue组件创建包装 。 该包装器是一个对象,其中包含已安装的组件和用于测试代码部分的方法。 然后,导入要在其上运行测试的Vue组件。

//testOne.spec.js
describe('HelloWorld.vue',function(){        it('Checking <h2> tag text',function(){                const wrapper = shallow(HelloWorld)        const h2= wrapper.find('h2')        expect(h2.text()).toBe('Essential Links')        })})

Then we create what we can call a test suite, using the describe() method of Mocha’s testing framework. This test suite basically groups multiple test cases into one along with providing some information about the tests and the component.

然后,我们使用describe()创建可以称为测试套件的内容 Mocha的测试框架的方法。 该测试套件基本上将多个测试用例归为一个,同时提供了有关测试和组件的一些信息。

In this describe function, we callback a function that specifies the test cases using the it() function. Each it() method describes a test case with the purpose of the test as the first parameter followed by a callback function defining the test.

在此describe函数中,我们回调使用it()函数指定测试用例的函数。 每个it()方法都将测试目的作为第一个参数描述一个测试用例,然后是定义测试的回调函数。

Then:

然后:

  • We create a wrapper of the Vue component我们创建Vue组件的包装
  • Use its find() method to get all <h2> tag elements

    使用其find() 获取所有<h2>标签元素的方法

  • Compare its text with what it is supposed to be.将其文字与预期文字进行比较。

Yay! Our test is ready to run.

好极了! 我们的测试已准备就绪。

npm run test

So, our test was successful — the code was able to find an <h2> tag in the HelloWorld.vue component with ‘Essential Links’ as its text.

因此,我们的测试成功了—代码能够在HelloWorld.vue组件中找到一个以'Essential Links'为文本的<h2>标签。

Now if we change the expected test to anything else, the test would fail. I changed it to:

现在,如果我们将预期的测试更改为其他任何测试,则测试将失败。 我将其更改为:

expect(h2.text()).toBe('Essential Linx')

and the test fails. The failed test error is quite descriptive, though, and you can see what the code was expecting and what it receives:

测试失败。 但是,失败的测试错误具有很强的描述性,您可以看到代码在期待什么以及收到了什么:

We can add multiple test cases in one test file by using multiple it() methods and expecting different conditions.

通过使用多种it()方法并期望不同的条件,我们可以在一个测试文件中添加多个测试用例。

describe('HelloWorld.vue',function(){
it('Checking <h2> tag text',function(){        const wrapper = shallow(HelloWorld)                const h2 = wrapper.find('h2')        expect(h2.text()).toBe('Essential Links')        }),
it('Checking <h1> tag text',function(){        const wrapper = shallow(HelloWorld)        const h1 = wrapper.find('h1')        expect(h1.text()).toBe('Welcome to Your Vue.js App')        })
})

Here we are also testing if the <h1> tag renders what it is supposed to.

在这里,我们还测试了<h1>标签是否呈现了预期的效果。

So this was a pretty basic test that just gives you an understanding of how tests are configured, coded, and run without even opening the browser or starting the server.

因此,这是一个非常基本的测试,仅使您了解测试的配置,编码和运行方式,而无需打开浏览器或启动服务器。

The link to the GitHub repository is here.

到GitHub存储库的链接在这里 。

结语 (Wrapping up)

Edd Yerburgh’s book ‘Testing Vue.js Applications’ helped me a lot in getting a wider picture of the importance of testing and how to implement it. I would recommend it to anyone who wants to learn testing beyond the scope of beginner-level content and really dive into it.

Edd Yerburgh的书“ Testing Vue.js Applications ”对我更广泛地了解测试的重要性以及如何实现它有很大帮助。 我将它推荐给想要学习超出初学者级内容范围并真正投入使用的任何人。

Other than that, I have been spending some time on TDD (Test Driven Development) concepts and am looking forward to writing a beginner’s tutorial about the world of TDD with Vue.js.

除此之外,我花了一些时间在TDD(测试驱动开发)概念上,并期待着用Vue.js编写有关TDD世界的初学者教程。

Please leave a clap or two if you liked the post. Thanks :)

如果喜欢的话,请拍一两拍。 谢谢 :)

翻译自: https://www.freecodecamp.org/news/testing-vue-js-applications-vue-test-utils-39ec26ddaa4e/

vue.js 全局应用js

vue.js 全局应用js_如何在不到7分钟的时间内测试您的Vue.js应用相关推荐

  1. 创建vue项目(二)引入elementUi、axios、准备静态资源、封装组件(.vue,js代码等)

    下载安装node -> vue-cli -> 配置路由 -> 引入elementUi -> 公共组件 一.引入elementUi 顺便一提axios使用说明 和axios在vu ...

  2. vue ui报错 Couldn‘t parse bundle asset “C:\Users\cqq\Desktop\vuex\vuex_demo\dist\js\chunk-vendors.js“.

    1. vue ui 运行编译项目时报错: Couldn't parse bundle asset  文件路径\\dist\js\chunk-vendors.js". Analyzer wil ...

  3. Vue + Spring Boot 项目实战(四):前后端结合测试(登录页面开发)

    前面我们已经完成了前端项目 DEMO 的构建,这一篇文章主要目的如下: ①打通前后端之间的联系,为接下来的开发打下基础 ②登录页面的开发(无数据库情况下) 文章目录 一.后端项目创建 1.1. 项目/ ...

  4. js中当等于最小值是让代码不执行_从浏览器多进程到JS单线程,JS运行机制最全面的一次梳理...

    前言 见解有限,如有描述不当之处,请帮忙及时指出,如有错误,会及时修正. ----------超长文+多图预警,需要花费不少时间.---------- 如果看完本文后,还对进程线程傻傻分不清,不清楚浏 ...

  5. Vue + Spring Boot 项目实战(三):前后端结合测试(登录页面开发)

    前面我们已经完成了前端项目 DEMO 的构建,这一篇文章主要目的如下: 一.打通前后端之间的联系,为接下来的开发打下基础 二.登录页面的开发(无数据库情况下) 本篇目录 前言:关于开发环境 一.后端项 ...

  6. Vue第二天学习总结—— Vue全家桶之组件化开发(组件化开发思想、组件注册、Vue调试工具用法、组件间数据交互传递、组件插槽、基于组件的案例——购物车)

    (一) 组件化开发思想 1. 现实中的组件化思想体现 组件化即是对某些可以进行复用的功能进行封装的标准化工作 标准:要想组件能够成功组合在一起,每个组件必须要有标准 分治:将不同的功能封装到不同的组件 ...

  7. 【实现js和css互通、共享常量参数值】js如何获取CSS/SCSS/LESS的常量、CSS/SCSS/LESS又是如何获取js的值(或者说js是如何主动推送参数给CSS使用的)?

    js获取CSS/SCSS/LESS的常量 <template><div id="body"><p>--color: {{ color }}< ...

  8. js控制css 加载,CSS样式表的加载对于DOM解析,渲染,JS执行的阻塞问题

    CSS加载问题 css加载会不会阻塞DOM树的解析? css加载会不会阻塞DOM树的渲染? css加载会不会阻塞后面js语句的执行? css阻塞 h1 { color: red !important ...

  9. 30 道 Vue 面试题,内含详细讲解(涵盖入门到精通,自测 Vue 掌握程度)

    -----------------------------------------原文链接------------------------------- 30 道 Vue 面试题,内含详细讲解(涵盖入 ...

最新文章

  1. mysql 避免使用NULL字段
  2. c调用按钮点击事件_React中事件的写法总结
  3. 笔记本电脑没有鼠标怎么右键_联想笔记本电脑没有声音怎么修复
  4. 神经网络 梯度下降_梯度下降优化器对神经网络训练的影响
  5. shell在一个大文件找出想要的一段字符串操作技巧
  6. java.rmi.server.port_java.rmi.server.ExportException: internal error: ObjID already in use报错处理...
  7. 同样双版本策略:索尼明年将有望推出PS5/PS5 Pro两款主机
  8. libtoolize: 未找到命令
  9. 基于STM32F103C8T6的74HC595驱动8位数码管模块学习
  10. PS去除图片中文字的方法详细图文教程
  11. 60著名条原则和定理
  12. [蓝桥杯] 三升序列 python解法
  13. (三)腾讯云开发工程师TCA题库(题目含详细解析)
  14. linux中24点游戏下载,怀旧24点官网版-怀旧24点游戏下载v2.0.0-Linux公社
  15. offiice2013全套软件,加破击工具,教程,真是验证过链接:https://pan.baidu.com/s/1Csv4ZXDQyK_cKfpIXwwn6Q 提取码:h7dp 复制这段内容后打
  16. 可以玩所有游戏的计算机配置,笔者教你玩大型游戏的电脑配置
  17. 软考高级 真题 2012年上半年 信息系统项目管理师 案例分析
  18. LeetCode.287 Find the Duplicate Number
  19. VLAN 的作用及access端口类型、trunk端口类型、hybrid端口类型之间的特性
  20. 蓝懿ios技术交流和心得分享 16.1.30

热门文章

  1. java小程序查看器,成功拿到offer
  2. SmartSVN:File has inconsistent newlines
  3. junit与spring-data-redis 版本对应成功的
  4. Linux 内存管理与系统架构设计
  5. Catalan数的理解
  6. fzu 1894 单调队列
  7. 可工作的软件胜过面面俱到的文档
  8. Jquery实现简单图片切换
  9. VS2005快捷键大全(转)
  10. Kafka 分布式环境搭建