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:
基本上有三種類型的測試:
- Unit tests 單元測試
- End to end tests 端到端測試
- 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