How to find broken links in a website using Cypress? - automation

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'))
})

Related

Nuxt.js: how to redirect inside methods

I'm learning Nuxt.js and I'm puzzled by how difficult it seems to be to simply redirect a user to another page from a method that is triggered via a click.
Here is the set up: I'm using Nuxt Auth to authenticate users, once authenticated I want them to be forwarded away from the signup page to another route. I already have middleware set up that redirect logged-in users, but it is only triggered when I refresh the page, not when I first log them in.
I have a method like this:
async login(event) {
event.preventDefault()
try {
await this.$auth.loginWith('local', this.loginData)
// this is where my redirect logic should go
} catch(error) { ... }
}
So far I've tried using this.$nuxt.refresh() which doesn't do anything at all and I've also tried this.$router.push('/route') which seems to hang the page completely. Ideally, I would prefer the refresh approach so that I don't have to specify the landing page for logged in users in multiple places, but I also need to know how to use redirections inside methods, I would have thought it should be the most simple operation imaginable and yet it seems to be difficult to find.
Any tips would be highly appreciated!
UPDATE:
I've found a solution, although it's not an ideal one. I've added an if-statement into beforeCreate that checks this.$auth.loggedIn and if it's true, then it calls this.$auth.redirect('home') when "home" is defined in nuxt.config.js under auth redirect. The reason this solution is not ideal is that it relies on the auth module (as opposed to being a general redirect mechanism).
There's a way in Nuxt to reload the page like so:
this.$router.go(0)
also you can find more information here
if this.$router is not working, try this
this.$nuxt.$options.router.push(url);

node express multer fast-csv pug file upload

I trying to upload a file using pug, multer and express.
The pug form looks like this
form(method='POST' enctype="multipart/form-data")
div.form-group
input#uploaddata.form-control(type='file', name='uploaddata' )
br
button.btn.btn-primary(type='submit' name='uploaddata') Upload
The server code looks like this (taken out of context)
.post('/uploaddata', function(req, res, next) {
upload.single('uploaddata',function(err) {
if(err){
throw err;
} else {
res.json({success : "File upload sucessfully.", status : 200});
}
});
})
My issue is that while the file uploads successfully, the success message is not shown on the same page, ie: a new page is loaded showing
{success : "File upload sucessfully.", status : 200}
As an example for other elements (link clicks) the message is displayed via such javascript:
$("#importdata").on('click', function(){
$.get( "/import", function( data ) {
$("#message").show().html(data['success']);
});
});
I tried doing a pure javascript in order to workaround the default form behaviour but no luck.
Your issue has to do with mixing form submissions and AJAX concepts. To be specific, you are submitting a form then returning a value appropriate to an AJAX API. You need to choose one or the other for this to work properly.
If you choose to submit this as a form you can't use res.json, you need to switch to res.render or res.redirect instead to render the page again. You are seeing exactly what you are telling node/express to do with res.json - JSON output. Rendering or redirecting is what you want to do here.
Here is the MDN primer on forms and also a tutorial specific to express.js.
Alternatively, if you choose to handle this with an AJAX API, you need to use jquery, fetch, axios, or similar in the browser to send the request and handle the response. This won't cause the page to reload, but you do need to handle the response somehow and modify the page, otherwise the user will just sit there wondering what has happened.
MDN has a great primer on AJAX that will help you get started there. If you are going down this path also make sure you read up on restful API design.
Neither one is inherently a better strategy, both methods are used in large-scale production applications. However, you do need to choose one or the other and not mix them as you have above.

Stencil redirect after login

Is there a good way to redirect to a specific page using Stencil right after logging in? It defaults to the my account, but want to send to main shop page. I know login.php?from= works, just not sure how to enforce that and looking for a better way.
I'd recommend a javascript redirect based on the referring URL, though it isn't ideal. There isn't a store setting to accomplish this.
if (document.referrer !== "http://www.stackoverflow.com") {
window.location.href = "http://www.google.com";
}
There are alternative scripts to accomplishing this that can be found if you look for "redirect by referring url" or "redirect based on previous page".

getJson method returns an error using woocommerce JSON API plugin

I'm using woocommerce JSON API to retrieve the data of some products like price, SKU, etc...
The thing is that I get an error using this API. I've installed the plugin succesfully and activated it in the WordPress Dashboard.
I've tried the example given in GitHub exactly as the author says.
Here's my javascript code:
$(document).on('pageinit','#restau' ,function(){
var url = 'http://danielvivancos.com/edu/wordpress/shop/?callback=?';
params = { action: 'woocommerce_json_api', proc:"get_products"};
params.arguments = {token: 1234, per_page: 2, page: 1}
jQuery.getJSON(url,params).done(function (data) {
alert("success");
console.log(data);
console.log(url);
}).error(function(jqXHR, textStatus, errorThrown){
alert(jqXHR.responseText);
});
});
At first it didn't do anything, and I didn't understand what was happening but then I added the .error() function and it threw me an error...
Here http://danielvivancos.com/edu/directebre_app_jquerymobile/ you will find the three alerts displayed when you click on any of the three products.
Hope someone can help me or give me some ideas to solve it.
Thank you all!
The API Almost always returns some kind of error string and error code. The one time when it wouldn't would be if there was a PHP error (Even then it tries to catch the error and return something).
One thing you may need to do is to visit the users settings page, setup your permissions, and then save the settings for that API User. Whenever a new method is added to the API you will have to visit this page and resave it.
Another thing to do is to try and run php tests/get_products.php and see what happens. Most of the API functions have a tests file that you can run from the command line to test the API.
Also, while I am very happy you are using it :) it is still unfinished and in the early stages of development.
It looks like your example is working though?
Could you post a bit more about what error you are getting?
When I click on one of the items, it takes me to a page where a popup shows up with a bunch of HTML, this normally means that your API page is not setup properly (if it is making an api request). You will need to setup the API page ( Just create a wordpress page, or use an existing one) Then in the WooCom menu select JSON Api, and set the API page from the dropdown list. Remember to save.

Apache rewrite for 404: getting the requested url

On my error page that I redirect to for any 404s, I'd like to record the url that the user tried to get to.
I've tried this but it doesn't work:
ErrorDocument 404 /error/?url=%{HTTP_REFERRER}
Can anyone tell me how to do it?
Try it with %{REQUEST_URI}. I'm not certain this will work in ErrorDocument since I've never tested it, but it's worth trying.
ErrorDocument 404 /error/?url=%{REQUEST_URI}
There isn't a direct way. Nor a perfect one. But there are few workarounds with PHP.
For example, I currently use a function to create the links of each page. So I would just need to add file_exists() to the main function (few lines in a single function).
This is the function I would use to create urls:
function url ($Value)
{
// Do some stuff with the url
// [Not showed]
if (!file_exists("/internal/path/".$Value))
{
// Call a function to store the error in a database
error ("404", $Value);
// One way of handling it. Replace '/' for ' ' and search that string.
// Example: "path/to/page" would become "path to page".
$Value=str_replace("/","%20",$Value);
return "http://www.example.com/search=".$Value;
}
else
{
// If the page exists, create the normal link.
return $FullUrl;
}
}
This is my regular way of creating an urls:
<?php url('path/to/page'); ?>
I just thought about this method. It's great as it allows you to find missing pages even IF the user doesn't click on the links. Thank you for making me think about it and now I'll use it in my page (:
Another 'simpler' method (in case you do not wrap links) is that you store last couple of pages visited in $_SESSION['lastpage']; and $_SESSION['lastlastpage'];, if 404 is found then store the corresponding page from which the user tried to access the broken page. It's not a perfect solution since you have to manually find the broken link in the previous page, but at least it gives you some idea of where it is.
Disadvantage: As you can see, both solutions ONLY work with internal broken links.
It would seem there isn't a way.