executing specific test files on cypress

Recently I was working on some Cypress tests, the first time I used them if I had to be honest, and I came across an issue. I wanted to run the test files individually but when I tried the solutions I found on the internet (StackOverflow and so on), no one of them worked for me. My setup was very bare, I didn’t even have a front end project as my tests involved sending requests to an API and asserting the HTTP responses, and the JSON values in the body. Being very new to Cypress I’m not sure if the following is the right way to go but I was executing the tests using command prompt and then reading the results using MochAwesome and an HTML file it produced. When researching online I read that there’s a some sort of a UI for running tests and reading results, but that was not my approach.

Instead I went for this approach. Inside the integration folder I created subfolders for each environment I wanted test. That is the reason why I had separate, individual files. Different environments have different credentials and environment variables. In the individual subfolders I had my JS test file. So roughly, my directory was like this

->root
  ->cypress
    ->integration
      ->development
        ->testfile.js
      ->staging
        ->testfile.js
      ->production
        ->testfile.js
  ->node_modules
  ->cypress.json
  ->package.json
  ->package-lock.json

Once I had that setup all I had to do was execute the following command on cmd.

npx cypress run --spec "cypress/integration/development/**"

Worth noting that if there had to be more than one JS test file inside a particular subfolder, say development, in that case all of the JS test files will be executed so yes I admit, technically speaking the title of this blog post isn’t accurate because this solution works for just one JS test file per subfolder, but hey who’s not guilty of implementing a not so clean solution?

Anyway, thanks for reading and I hope this is useful to some frustrated developer who can’t find a way to run cypress tests the way he/she wishes.

See you next post,
Bjorn

implementing a cascading dropdown list with MVC and Jquery

By definition (my own) a cascading dropdown list(s) is a set of dropdown list(s) dependent on their parent dropdown list. In this blog post we’ll see how this can be achieved in ASP.NET’s MVC pattern, with the help of some client-side scripting too. For simplicity I will be using the standard template that Visual Studio creates for you when you create a new project. Also, I uploaded the source code to this GitHub location.

All right so let’s say that we’re going to have three dropdown lists, and through these we will be able to drill down from continent, to countries, to cities. All the data in this project is hard coded but it can easily be retrieved from a database or some other source. So first thing we’ll do is update the Index method in the HomeController to make it look like the following;


public ActionResult Index()
{
continents = new List();
continents.Add(new SelectListItem { Text = "Select continent", Value = "0" });
continents.Add(new SelectListItem { Text = "Europe", Value = "1" });
continents.Add(new SelectListItem { Text = "North America", Value = "2" });
continents.Add(new SelectListItem { Text = "South America", Value = "3" });
ViewData["continents"] = continents;
countries = new List();
countries.Add(new SelectListItem { Text = "Select country", Value = "0" });
ViewData["countries"] = countries;
cities = new List();
cities.Add(new SelectListItem { Text = "Select city", Value = "0" });
ViewData["cities"] = cities;
return View();
}

So we created three lists of type SelectListItem and filling them with some data, and then passing them to our view using the ViewData. These lists can also be bound to a model and then pass the model to the view. I chose the ViewData option for simplicity. Within the view we need to create three dropdown lists and make a reference to the ViewData.


<div class="row">
<div class="col-md-4">
@Html.DropDownList("continents", ViewData["continents"] as List)
</div>
<div class="col-md-4">
@Html.DropDownList("countries", ViewData["countries"] as List)
</div>
<div class="col-md-4">
@Html.DropDownList("cities", ViewData["cities"] as List)
</div>
</div>

Now we got three dropdown lists with some data in them. For the next part we need to add some client-side scripting so we can load more data dynamically. Using Jquery we will make an AJAX call and get data according to what the user selected.


$("#continents").change(function () {
$("#countries").empty();
$.ajax({
type: 'POST',
url: '/Home/GetCountries',
dataType: 'json',
data: { selectedValue: $("#continents").val() },
success: function (areas) {
$.each(areas, function (i, area) {
$("#countries").append('' + area.Text + '');
});
},
error: function (ex) {
alert('Failed to retrieve countries.' + ex);
}
});
return false;
});
$("#countries").change(function () {
$("#cities").empty();
$.ajax({
type: 'POST',
url: '/Home/GetCities',
dataType: 'json',
data: { selectedValue: $("#countries").val() },
success: function (cases) {
$.each(cases, function (i, ucase) {
$("#cities").append('' + ucase.Text + '');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
return false;
});

Back to the HomeController we are going to create two entry points and do our logic in there.


public JsonResult GetCountries(string selectedValue)
{
countries = new List();
countries.Add(new SelectListItem { Text = "Select country", Value = "0" });
switch (selectedValue)
{
case "1":
countries.Add(new SelectListItem { Text = "United Kingdom", Value = "1" });
countries.Add(new SelectListItem { Text = "Italy", Value = "2" });
countries.Add(new SelectListItem { Text = "Greece", Value = "3" });
break;
case "2":
// more countries
break;
case "3":
// more countries
break;
}
return Json(new SelectList(countries, "Value", "Text"));
}
public JsonResult GetCities(string selectedValue)
{
cities = new List();
cities.Add(new SelectListItem { Text = "Select city", Value = "0" });
switch (selectedValue)
{
case "1":
cities.Add(new SelectListItem { Text = "Glasgow", Value = "1" });
cities.Add(new SelectListItem { Text = "London", Value = "2" });
cities.Add(new SelectListItem { Text = "Edinburgh", Value = "3" });
break;
case "2":
// more cities
break;
case "3":
// more cities
break;
case "4":
// more cities
break;
case "5":
// more cities
break;
// more cases
}
return Json(new SelectList(cities, "Value", "Text"));
}

And that should be it. Feel free to share your thoughts if you have any suggestions. Until the next post.

Bjorn

improving a website’s performance – part 1

If we had to look back to the dial-up days and compare the internet and overall world wide web experience, we can all agree that the improvement, particularly in speed, was life-changing. Yes I dare to use that word. Nowadays we are able to download large chunks of data in a bat of an eye but we should not rely on such commodity and become lazy developers knowing that the reliability of the internet will cover our mistakes. Instead we should always seek ways how to improve our product, in this case a website, and make sure that the user has a better user experience. Therefore, here’s my take at improving a website’s performance using simple tricks, methodologies and implementations.

Minify resources

When I code I like to keep everything structured and formatted, including the source code itself. It easier to read and maintain but the same structure is being processed and outputted by the web browser. Therefore the user would be downloading extra unnecessary characters such as carriage returns, white spaces, comments and any other characters that if removed the source code would still function as supposed to … not cool bro! Minify your resources, mainly JavaScript and CSS files(but it could be any file you’re serving over the web), to make file sizes smaller. More recently, latest minification processes also shorten variable and function names to further reduce the character count in that file. The main advantage of reducing a file size is to consume less of the user’s bandwidth and therefore loading the website faster. There are loads of tools, applications and online tools, that can be used to minify your files. I’m sure that a quick Google search will guide you to the right places.

Minimise HTTP requests

Every time a user visits your website and each web page on your website, or even if the same page is refreshed, the user is downloading all the resources needed to load the page. Every refresh … download … resources … let that sink in. Said resources would include the HTML itself, images, stylesheet files, JavaScript files along with other files being requested on page load. And for each and every file an HTTP request is triggered in order to get the data. These HTTP requests can be minimised by combining certain files together into one file, such as reducing 5 different CSS files into 1 CSS file which translates to reducing 5 HTTP requests into 1. Having said that try to combine files intelligently. If a certain JS file is specific for the Gallery page only, don’t combine it to the “main JS file” where it is being called by each and every page.

Optimise images

To further reduce the user’s bandwidth consumption consider optimising your images which could easily be the most resource hungry files in your website. Certain graphics can be generated with CSS instead of an image. For instance, set the background color of a button using CSS instead of setting the background image property and pointing it towards an image. Other times you have no choice but to use the actual image, such as when displaying your product. In that case, optimise your images starting off with reducing their sizes. It’s useless making the browser download a 2500 pixel image to be then set to 500 pixels and set as a thumbnail of your product. Use image editing software to resize your images. While you’re at it, why not compress the image too to further reduce the image size? Compressing images reduces the image quality by removing “extra” colour profiles and tags which are not required for the web but will still make it look great when viewed in a website. Photoshop has a specific feature for that, Save for Web. Lastly, save your images in the correct format. Stick to JPEG for images and PNG for graphics and avoid using BMP and TIFF.

In this first part we had a look at ways how our website’s response time can be improved. In the second part, we will discover other beneficial implementations and also tools that can be used to grade our website’s performance. Stay tuned for more and until next time,

Bjorn