乐闻世界logo
搜索文章和话题

How to check all links in cypress without stopping in case of an error

1个答案

1

In Cypress, to verify if all links on a web page are accessible, you can write a test that iterates through each link and performs a GET request to validate the response status. To ensure the test does not halt when errors occur, you can use .then() and .catch() to handle success and error scenarios, or configure Cypress's .request() method to ignore errors.

Here is an example test script written in Cypress that iterates through all <a> tag elements on the page and makes requests to each link to check its accessibility:

javascript
describe('Link Accessibility Test', () => { it('should be able to access all links on the page', () => { cy.visit('https://example.com'); // Replace with the URL of the page you want to test cy.get('a').each(($a) => { const href = $a.prop('href'); if (href) { cy.request({ url: href, failOnStatusCode: false // This ensures the test does not fail when the response status code is 4xx or 5xx }).then((response) => { expect(response.status).to.be.oneOf([200, 301, 302]); // This lists the acceptable response status codes }); } }); }); });

In this example, the cy.get('a') command retrieves all links on the page. The each() function iterates through these links and executes an action on each one. Here, the action is sending a GET request using cy.request() to the URL specified by the href attribute of the link.

By default, the cy.request() command causes the test to fail if the response status code is 4xx or 5xx. To prevent this, set failOnStatusCode: false, ensuring the test does not halt even if the request fails.

Within the .then() callback, we verify that the response status code matches the acceptable codes we defined. For instance, 200 typically indicates a successful request, while 301 and 302 indicate redirects. Adjust this list as needed based on your requirements.

Note that this test only confirms links can be successfully accessed and does not validate whether the target content of the links is correct or valid. Additionally, not all links should return a 200 status code; some may intentionally return other status codes. Depending on your specific needs, you may need to adjust this script accordingly.

2024年6月29日 12:07 回复

你的答案