How can I find all broken links in a website using Cypress if there are any? Are there any plugins to use?
If not, how should I write my code that I can see whether the link returns a 200
status (or a successful link)?
Thank you!
How can I find all broken links in a website using Cypress if there are any? Are there any plugins to use?
If not, how should I write my code that I can see whether the link returns a 200
status (or a successful link)?
Thank you!
Maybe this?
cy.request('yourlink')
.should((response) => {
expect(response.status).to.eq(200)
})
Try this...
for the first a selection a[href*="yourdomain.com"]
the reason I didn't include "www" is because for my project we link to subdomains as well so I needed to include these.
for the second half, :not([href=""]
, again for my project we had links like this for some reason so I had to make sure to NOT include it.
$el.prop("href")
fetches the href value from the DOM element.
I'm using cy.request()
to send a HTTP request to the URL and make sure that it returns 200
thus proving that the page exists.
Here's the code:
cy.get('a[href*="yourdomain.com"]:not([href=""])').each(($el) => {
cy.request($el.prop("href")).as("link");
});
cy.get("@link").should((response) => {
expect(response.status).to.eq(200);
});
You can use this for any page. You can have your pages listed out in your cypress.json
file or you can do it programatically as a regression test.
Here's the simplest way to do it:
cy.request("yourLink")
Yes, no need to add any assertions. because by default there's an assertion that the response is not 404. so this line is more than enough.
If you want to go the extra mile and test all the links in the page, here's what to do:
cy.get('a').each(link => {
cy.request(link.prop('href'))
})
This should make a request to all the available links with a tag in the page.
cy.visit(link)
cy.get('a').each(page => {
cy.request(page.prop('href'))
})