当前位置: 首页 > 工具软件 > BigPicture.js > 使用案例 >

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

堵雅健
2023-12-01

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

 类似资料: