賽普拉斯 12864
In my previous post, I covered how to add screenshot testing in Cypress to ensure components don't unintentionally change over time.
在上一篇文章中 ,我介紹了如何在賽普拉斯中添加屏幕截圖測試,以確保組件不會隨時間變化。
Now, I will share how to automate accessibility tests with Cypress.
現在,我將分享如何與賽普拉斯自動執行輔助功能測試。
我們為什么要關心可訪問性? (Why should we care about accessibility?)
Short answer: because it is the right thing to do.
簡短答案:因為這是正確的做法。
Long answer: an accessible web can help people with disabilities improve their lives.
長答案:可訪問的網絡可以幫助殘疾人改善生活。
There are different kinds of disabilities, including auditory, cognitive, neurological, physical, speech and visual. And our goal as product creators, engineers, and designers is to create experiences that include all people.
有多種類型的殘疾,包括聽覺,認知,神經,身體,語言和視覺。 我們作為產品創造者,工程師和設計師的目標是創造包括所有人的體驗。
It is also important to mention that web accessibility also benefits people without disabilities.
同樣重要的是要提的是網頁易讀也有利于非殘疾人。
For example, accessible sites help people with changing abilities due to ageing or people with slow Internet connections or those using devices with small screens.
例如,可訪問的站點可以幫助因年齡增長或互聯網連接速度緩慢或使用小屏幕設備的人而改變能力。
And a disability can also be temporary. For example, someone with a broken arm can't type and use a mouse at the same time.
殘疾也可以是暫時的。 例如,手臂骨折的人不能同時鍵入和使用鼠標。
If you want to educate yourself about the topic, I can recommend the W3C Web Accessibility Initiative (W3C WAI) and The A11Y Project.
如果您想對這個主題進行自我教育,我可以推薦W3C Web Accessibility Initiative(W3C WAI)和A11Y Project 。
輔助功能測試技術 (Accessibility testing techniques)
There are different ways to test if your website/app is accessible. The W3C WAI has a list of 140+ tools to help you determine if your website/app meets accessibility guidelines.
有多種測試網站/應用程序是否可訪問的方法。 W3C WAI 列出了140多種工具 ,可幫助您確定您的網站/應用是否符合輔助功能準則。
You can also add in your strategy:
您還可以添加策略:
Real user testing: companies like Fable connect you and people with disabilities so that your research and user testing can help you meet your compliance goals.
真實的用戶測試:像Fable這樣的公司將您與殘疾人聯系起來,以便您的研究和用戶測試可以幫助您實現合規性目標。
Browser extensions: axe is a recommended extension for Chrome, Firefox, and Edge that helps identify and resolve common accessibility issues.
瀏覽器擴展: ax是Chrome,Firefox和Edge的推薦擴展,可幫助識別和解決常見的輔助功能問題。
The accessibility engine of axe is open-source and it can be used in different ways, as this post will show.
正如本文將顯示的那樣,ax的可訪問性引擎是開源的 ,可以以不同的方式使用它。
開始之前 (Before we start)
I created a sample website to mimic a Component Library. It is a very simple website created with Tailwind CSS and hosted in Vercel and it documents 2 components: badge and button.
我創建了一個示例網站來模仿組件庫。 這是一個使用Tailwind CSS創建的非常簡單的網站,并托管在Vercel中,它記錄了2個組件: badge和button 。
You can check out the source code on GitHub. The website is static and it is inside the public
folder. You can see the website locally by running npm run serve
and checking in the browser http://localhost:8000.
您可以在GitHub上查看源代碼 。 該網站是靜態的,并且位于public
文件夾中。 您可以通過運行npm run serve
并在瀏覽器中查看http:// localhost:8000來在本地查看該網站。

添加柏樹和柏樹軸 (Adding Cypress and cypress-axe)
Start by cloning the example repository. Next, create a new branch and install cypress-axe, the package responsible for tying the axe engine to Cypress.
首先克隆示例存儲庫 。 接下來,創建一個新分支,并安裝cypress-axe ,該軟件包負責將斧頭引擎綁定到Cypress。
git checkout -b add-cypress
npm install -D cypress cypress-axe
Next, create a cypress/support/index.js
file containing:
接下來,創建一個包含以下內容的cypress/support/index.js
文件:
import 'cypress-axe'
This import will inject all the functions we need for our tests.
此導入將注入我們測試所需的所有功能。
創建可訪問性測試 (Creating the accessibility test)
Time to create the accessibility test. Here is the plan:
是時候創建可訪問性測試了。 這是計劃:
- Cypress will visit each page (badge and button) of the project. 賽普拉斯將訪問該項目的每個頁面(徽章和按鈕)。
Cypress will test each example in the page. The Badge page has 2 examples (Default and Pill), while the Button page has 3 examples (Default, Pill and Outline).
賽普拉斯將測試頁面中的每個示例。 徽章頁面有2個示例(默認和藥丸),而按鈕頁面有3個示例(默認,藥丸和輪廓)。
All these examples are inside an <div>
element with a cypress-wrapper
. This class was added with the only intention to identify what needs to be tested.
所有這些示例都在帶有cypress-wrapper
的<div>
元素內。 添加該類的唯一目的是確定需要測試的內容。
The first step is creating the Cypress configuration file (cypress.json
):
第一步是創建賽普拉斯配置文件( cypress.json
):
{"baseUrl": "http://localhost:8000/","video": false
}
The baseUrl
is the website running locally. As I mentioned before, npm run serve
will serve the content of the public
folder. The second option, video
disables Cypress video recording, which won't be used in the project.
baseUrl
是在本地運行的網站。 正如我前面提到的, npm run serve
將服務內容public
文件夾。 第二個選項, video
禁用賽普拉斯的視頻記錄,該記錄將不會在項目中使用。
Time to create the test. In cypress/integration/accessibility.spec.js
, add:
是時候創建測試了。 在cypress/integration/accessibility.spec.js
,添加:
const routes = ['badge.html', 'button.html'];describe('Component accessibility test', () => {routes.forEach((route) => {const componentName = route.replace('.html', '');const testName = `${componentName} has no detectable accessibility violations on load`;it(testName, () => {cy.visit(route);cy.injectAxe();cy.get('.cypress-wrapper').each((element, index) => {cy.checkA11y('.cypress-wrapper',{runOnly: {type: 'tag',values: ['wcag2a'],},});});});});
});
In the code above, I am creating dynamic tests based in the routes
array. The test will check each .cypress-wrapper
element against WCAG 2.0 Level A rules.
在上面的代碼中,我正在基于routes
數組創建動態測試。 該測試將對照WCAG 2.0 A級規則檢查每個.cypress-wrapper
元素。
There are different standards / purposes, as the table below shows:
下表顯示了不同的標準/目的:
Tag Name | Accessibility Standard / Purpose |
---|---|
wcag2a | WCAG 2.0 Level A |
wcag2aa | WCAG 2.0 Level AA |
wcag21a | WCAG 2.1 Level A |
wcag21aa | WCAG 2.1 Level AA |
best-practice | Common accessibility best practices |
wcag*** | WCAG success criterion e.g. wcag111 maps to SC 1.1.1 |
ACT | W3C approved Accessibility Conformance Testing rules |
section508 | Old Section 508 rules |
section508.*.* | Requirement in old Section 508 |
標簽名 | 無障礙標準/目的 |
---|---|
wcag2a | WCAG 2.0 A級 |
wcag2aa | WCAG 2.0 AA級 |
wcag21a | WCAG 2.1 A級 |
wcag21aa | WCAG 2.1 AA級 |
best-practice | 通用無障礙最佳做法 |
wcag*** | WCAG成功標準,例如wcag111映射到SC 1.1.1 |
ACT | W3C批準的可訪問性一致性測試規則 |
section508 | 舊版508條規定 |
section508.*.* | 舊版508節的要求 |
You can find more information about it in the axe-core docs.
您可以在axe-core docs中找到有關它的更多信息。
Last, let's create inside the package.json
command to trigger the tests:
最后,讓我們在package.json
命令內部創建以觸發測試:
{"test": "cypress"
}
From here, there are 2 options: run Cypress in headless mode with npm run cypress run
or use the Cypress Test Runner with npm run cypress open
.
從這里開始,有2個選項:使用npm run cypress run
在無頭模式下運行Cypress或在npm run cypress open
使用Cypress Test Runner。
無頭選項 (Headless option)
Using npm run test run
, the output should be similar to the next image:
使用npm run test run
,輸出應該類似于下一個圖像:

The tests will pass since the components have no accessibility issues.
由于組件沒有可訪問性問題,因此測試將通過。
測試運行器選項 (Test Runner option)
Using npm run test open
, Cypress Test Runner will be opened and you can follow step by step the tests.
使用npm run test open
,賽普拉斯Test Runner將被打開,您可以逐步進行測試。

Our first milestone is done. Let's merge this branch to master. If you want to see the work done so far, jump in my Pull Request.
我們的第一個里程碑已經完成。 讓我們將該分支合并到master。 如果您想查看到目前為止已完成的工作,請進入我的請求請求 。
現實生活中的測試 (Testing in real life)
Imagine we are updating the website and we want to identify the buttons with ids. The id
property must be unique in the document, as we can't have 2 elements with the same one. But we forgot about that and 3 buttons have the same id.
想象一下,我們正在更新網站,并且想要標識具有ID的按鈕。 id
屬性在文檔中必須是唯一的,因為我們不能有2個元素具有相同的元素。 但是我們忘記了這一點,并且3個按鈕具有相同的ID。
Cypress will fail and the output will look something like this:
賽普拉斯將失敗,并且輸出將類似于以下內容:

Let's improve the output of our tests by showing a table of found issues. First, let's create a new branch:
通過顯示已發現問題的表格,讓我們改善測試的輸出。 首先,讓我們創建一個新分支:
git checkout -b improve-cypress-tests
Next, create the cypress/plugins/index.js
file with the following content:
接下來,使用以下內容創建cypress/plugins/index.js
文件:
module.exports = (on, config) => {on('task', {log(message) {console.log(message)return null},table(message) {console.table(message)return null}})
}
This will execute code in Node via the task
plugin event of Cypress. Next, let's go back to the accessibility.spec.js
file and add the following function in the top of the file:
這將通過賽普拉斯的task
插件事件在Node中執行代碼。 接下來,讓我們回到accessibility.spec.js
文件,并在文件頂部添加以下功能:
const terminalLog = (violations) => {cy.task('log',`${violations.length} accessibility violation${violations.length === 1 ? '' : 's'} ${violations.length === 1 ? 'was' : 'were'} detected`)// pluck specific keys to keep the table readableconst violationData = violations.map(({ id, impact, description, nodes }) => ({id,impact,description,nodes: nodes.length}))cy.task('table', violationData)
}
The violations
array contains all information about the failing elements. You can tweak this code to include, for instance, the element source code in the test output.
violations
數組包含有關失敗元素的所有信息。 您可以調整此代碼以在測試輸出中包括例如元素源代碼。
Last, let's call the function inside the tests. Modify the checkA11y
function to:
最后,讓我們在測試中調用該函數。 將checkA11y
函數修改為:
cy.checkA11y('.cypress-wrapper',{runOnly: {type: 'tag',values: ['wcag2a'],},},terminalLog,
);
When you run the test again, you'll get a table containing the issues reported by axe:
再次運行測試時,您將獲得一個包含斧頭報告的問題的表:

If you have any questions, please check the Pull request in Github.
如有任何疑問,請檢查Github中的Pull請求 。
下一步 (Next steps)
From here, you can continue your journey toward making products more accessible. As some next steps, I would recommend:
從這里開始,您可以繼續努力,使產品更易于使用。 作為下一步,我建議:
Adding these tests in your CI solution - I wrote about integrating Cypress inside Semaphore
在您的CI解決方案中添加這些測試-我寫過有關將Cypress集成到Semaphore中的信息
- Finding the best way to customize the output of tests to improve troubleshooting issues 尋找自定義測試輸出以改善故障排除問題的最佳方法
- Learning more about how axe works. 了解有關斧頭工作原理的更多信息。
I hope that you have learned that accessibility testing is not difficult and it doesn't require much to start. Automation powered by axe can definitely help us to create better user experiences for all people.
我希望您了解到可訪問性測試并不困難,并且不需要太多的開始。 由斧頭驅動的自動化絕對可以幫助我們為所有人創造更好的用戶體驗。
--
-
Questions? Comments? This post is also in my blog. If you like this content, follow me on Twitter and GitHub.
有什么問題嗎 注釋? 這篇文章也在我的博客中 。 如果您喜歡此內容,請在Twitter和GitHub上關注我。
翻譯自: https://www.freecodecamp.org/news/automating-accessibility-tests-with-cypress/
賽普拉斯 12864