How can we help?

JavaScript functions – tips and tricks

You are here:

In order to create reliable, maintainable and reusable JavaScript functions, we prepared a list of best practices for you and your team.

Make your functions easy to be manually tested in the browser

The easiest way to create and test javascript functions, is to avoid mixing your code with function parameters. Ideally, you should define all the variables at the beginning of the function and save the results at the end of the function. This way, you can easily execute the code in the browser console on your application page to make sure it does what you expect. See the following example:

function trudonJSStep(element, callbacks, builtinVars, customVars)
{
  // variables definition
  var customClass = customVars.customClass;
  var classFound = false;
  
  // your desired code
  if (element.className.split(' ').indexOf(customClass) >= 0) {
    classFound = true;
  }
  
  // saving vars and finishing execution
  if (classFound) {
    callbacks.pass("Desired class found!");
  } else {
    callbacks.fail("Desired class not found!");
  }

  customVars.classFound = classFound;
  callbacks.done();
}

Test your JavaScript code in your own browser console

To make sure that your code works as expected, you should always test it in your own browser console before using them in your tests.

Use generic names for custom variables

If your function expects two variable like birthDate, and minimumAge, it is not very generic. You can’t reuse it in tests where you want to check that the difference between two custom dates is bigger than a desired period. A better approach would be to have something like this:

function trudonJSStep(element, callbacks, builtinVars, customVars)
{
  // variables definition
  var minDate = customVars.minDate | Date.now();
  var maxDate = customVars.maxDate | Date.now();
  var difference = customVars.difference;
  var datesHaveDifference = false;
  
  // your desired code
  if (maxDate - minDate >= difference) {
    datesHaveDifference = true;
  }
  
  // saving vars and finishing execution
  if (datesHaveDifference) {
    callbacks.pass("Dates desired difference met!");
  } else {
    callbacks.fail("Dates desired difference not met!");
  }

  customVars.datesHaveDifference = datesHaveDifference;
  callbacks.done();
}

Avoid interacting with your page elements directly

It is not a good practice to handle click actions or to write text in inputs directly from your JavaScript functions. Using JavaScript to perform such actions does not mimic a real user and your application might behave differently. It is always recommended to use Trudon’s built-in actions, potentially with variables defined in your previously executed JavaScript functions.

Was this article helpful?
0 out Of 5 Stars
5 Stars 0%
4 Stars 0%
3 Stars 0%
2 Stars 0%
1 Stars 0%
How can we improve this article?
Need help?