vue.js 全局應用js_如何在不到7分鐘的時間內測試您的Vue.js應用

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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394806.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394806.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394806.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

MongoDB在Linux下常用優化設置

MongoDB在Linux下常用優化設置以下是一些MongoDB推薦的常用優化設置。在生產環境下選取合適的參數值&#xff0c;例如預讀值和默認文件描述符數目等&#xff0c;會對系統性能有很大的影響。1、關閉數據庫文件的 atime禁止系統對文件的訪問時間更新會有效提高文件讀取的性能。這…

iOS常用第三方庫大全,史上最全第三方庫收集

下拉刷新 EGOTableViewPullRefresh – 最早的下拉刷新控件。SVPullToRefresh – 下拉刷新控件。MJRefresh – 僅需一行代碼就可以為UITableView或者CollectionView加上下拉刷新或者上拉刷新功能。可以自定義上下拉刷新的文字說明。具體使用看“使用方法”。 &#xff08;國人寫…

ipconfig沒有顯示ip_TCP/IP 協議修復網絡問題

nternet 在 TCP/IP 協議上工作&#xff0c;如果 TCP/IP 協議堆棧在 Windows 或任何其他操作系統(例如 Linux 或 MacOS)中無法正常工作&#xff0c;則您的 Internet 連接會出現問題。解決 Internet 問題的最佳方法是重置 TCP/IP 堆棧設置。如何在 Windows 中重置 TCP/IP 堆棧&am…

mysql卸載

先執行mysql安裝程序&#xff0c;點擊移除&#xff0c;然后再刪除對應的安裝路徑&#xff0c;必要的時候還要刪除注冊表信息。轉載于:https://www.cnblogs.com/772933011qq/p/6007752.html

mysql-linux64,Linux64下mysql安裝和開辟

1.1地址&#xff1a;http://www.mysql.com/downloads/mysql/5.5.html&#xff03;downloads版本&#xff1a;5.1.68平臺&#xff1a;linux generalGeneric Linux (glibc 2.3) (x86&#xff0c; 64-bit)&#xff0c; RPM Package版本&#xff1a;MySQL Server(MySQL-server-5.1.…

mysql 內置功能 存儲過程 目錄

mysql 內置功能 存儲過程介紹mysql 內置功能 存儲過程 創建無參存儲過程mysql 內置功能 存儲過程 創建有參存儲過程mysql 內置功能 存儲過程 刪除存儲過程轉載于:https://www.cnblogs.com/mingerlcm/p/10533021.html

簡化C語言文法

程序 → 外部聲明|程序 外部聲明 外部聲明 → 定義函數|定義 函數定義 → 類型標識符 聲明部分語句 類型標識符 → 空類型|字符型|整型|浮點型 聲明部分語句 → 指針 直接聲明|直接聲明 指針 → * |* 指針 直接聲明 → 標識符 | 直接聲明[ ] | 直接聲明[常數表達式] | 標識符&a…

elixir 規格_Elixir:一種高畫質的編程語言

elixir 規格by CityBase按CityBase Elixir&#xff1a;一種高畫質的編程語言 (Elixir: A Big-Picture Programming Language) Elixir使程序員的工作更好&#xff0c;并且使他們的工作更好 (Elixir makes programmers better at their work, and it makes their work better) A…

python截圖識別文字_用百度ocr+微信截圖實現文字識別

作用&#xff1a;將圖片中的文字識別出來 一、調用微信截圖dll控件 將微信截圖插件復制到項目文件&#xff0c;使用ctypes加載&#xff08;膠水語言就是給力&#xff09; def capture(): try: dll ctypes.cdll.LoadLibrary(PrScrn.dll) except Exception: print("Dll loa…

MySQL啟動很慢的原因

我們在啟動MySQL的時候&#xff0c;常常會遇到的是&#xff0c; 當執行啟動命令后&#xff0c;它會"Start MySQL ....." 一直不停的執行&#xff0c;也不中斷&#xff0c;也不成功 這里會出現此現象的原因有以下三條&#xff1a; 1. 配置文件中的InnoDBuffer數大于物…

linux線程出錯,在線程應用程序(linux,pthreads)中讀取文件大小時出錯

我試圖從Linux中的文件夾中讀取所有文件和目錄&#xff0c;其線程為 獲取最大文件大小&當前目錄和當前目錄樹下的名稱。在線程應用程序(linux&#xff0c;pthreads)中讀取文件大小時出錯主線程掃描基本目錄查找文件&#xff0c;當找到它的目錄時&#xff0c;會生成一個新線…

【用jQuery來判斷瀏覽器的類型】及【javascript獲取用戶ip地址】

用jQuery來判斷瀏覽器的類型,主要是使用$.browser這個工具類,使用方法: $.browser.[瀏覽器關鍵字] //谷歌瀏覽器、360瀏覽器等其他一些瀏覽器&#xff0c;沒有專門的判斷 function appInfo() {var bro $.browser;var binfo "";if (bro.msie) {binfo "Micr…

python函數學習1

函數1 &#xff08;1&#xff09;定義&#xff1a; def 函數名&#xff08;參數列表&#xff09;函數體 &#xff08;2&#xff09;參數傳遞&#xff1a; 在python中&#xff0c;一切都是對象&#xff0c;類型也屬于對象&#xff0c;變量是沒有類型的。 a [1,2,3] a "he…

kafka應用于區塊鏈_Apache Kafka的區塊鏈實驗

kafka應用于區塊鏈by Luc Russell盧克羅素(Luc Russell) Apache Kafka的區塊鏈實驗 (A blockchain experiment with Apache Kafka) Blockchain technology and Apache Kafka share characteristics which suggest a natural affinity. For instance, both share the concept o…

pythonfor循環100次_以寫代學: python for循環 range函數 xrange函數

腳本一&#xff1a; #!/usr/bin/env python # coding: utf8 sum100 0 for i in range(101): sum100 i #&#xff08;1&#xff09;range是一個可以取值的函數&#xff0c;上邊這個取的是0-100&#xff0c;并不包含101 #&#xff08;2&#xff09;也可以指定&#xff0c;比如r…

iis下php 500錯誤

很不想用iis&#xff0c;然而客戶不想增加機器&#xff0c;只好按客戶的意思了。可是沒想到發送短信以在本地 機器上是好的&#xff0c;在iis下直接500。 ??一開始以為是防火墻問題&#xff0c;后來檢查了一下沒有&#xff0c;再后來換了一個短信接口&#xff0c;就莫名其妙好…

linux mv 遞歸拷貝,奇技淫巧 - 給Linux中的cp和mv命令中添加進度條的高級拷貝

GNU cp和GNU mv命令用于在GNU/Linux操作系統中復制和移動文件和目錄。這兩個命令缺少的一個特性是它們不顯示任何進度條。如果復制一個大文件或目錄&#xff0c;您就不知道完成復制過程需要多長時間&#xff0c;也不知道復制的數據所占的百分比。還有您將看不到當前正在復制哪個…

webgl 著色器_如何在WebAssembly中使用WebGL著色器

webgl 著色器by Dan Ruta通過Dan Ruta 在WebAssembly中使用WebGL著色器 (Using WebGL shaders in WebAssembly) WebAssembly is blazing fast for number crunching, game engines, and many other things, but nothing can quite compare to the extreme parallelization of …

【洛谷P1966】火柴排隊

兩列排序后將編號一一對應 歸并排序求逆序對 &#xff08;每一次交換就去掉一個逆序對&#xff09; 1 #include<cstdio>2 #include<cstring>3 #include<algorithm>4 #define ll long long5 using namespace std;6 const int N100100;7 const ll P99999997;8 …

python字符串補空格輸出_Python去除空格,Python中常見字符串去除空格的方法總結...

今天小編就為大家分享一篇關于Python去除字符串前后空格的幾種方法&#xff0c;小編覺得內容挺不錯的&#xff0c;現在分享給大家&#xff0c;具有很好的參考價值&#xff0c;需要的朋友一起跟隨小編來看看吧&#xff1a; Python去除空格方法一&#xff1a; strip()方法&#x…