Skip to main content
  • Home
  • Blog
  • Sandbox

Alvin Pascoe

Website Developer

Alvin Pascoe
Loading.....
  • Drupal 7 Dynamic Content Carousel - Carousel Transitions
    Drupal 7 Dynamic Content Carousel - Carousel Transitions
  • JavaScript Memoisation
    JavaScript Memoisation

JavaScript assert() Function

9th September, 2015

Whenever you code, testing is vital. Test early and often.

With this in mind, it can be useful to create a function that is used purely for testing.

The assert function is written in pure JavaScript and can be used to make assertion when coding.

/**
 * Used to test assertions.
 * @param {boolean} value - Test expression which is expected to return true.
 * @param {string} description - Description of the assertion.
 * @param {boolean} list - True displays results in a list, false returns to console.
 */
function assert(value, description, list){

  //If the list parameter is not defined, output to console
  if (list === undefined || list === false){
    description = value ? "PASS - " + description : "FAIL - " + description;
    console.log(description);
  }else{
    //Else, display results in a list on the page

    //Check if results list exists. If not, create it.
    if(document.getElementById("test-results") === null){
      var results = document.createElement("ul");
      results.id = "test-results";
      document.body.appendChild(results);
    }

    //Create a new list item and add its class and prefix based on the 'value' parameter
    var test = document.createElement("li");
    test.className = value ? "pass" : "fail";
    description = value ? "PASS - " + description : "FAIL - " + description;
    test.appendChild(document.createTextNode(description));

    //Add list item to results list
    document.getElementById("test-results").appendChild(test);
  }
  
}

//assert(1 == 1, "This test passes, the results are printed to the console");
//assert(1 == 2, "This test fails, the results are printed to the page", true);
  • JavaScript
  • Previous Article: Drupal 7 Dynamic Content Carousel - Carousel Transitions
    Previous Article: Drupal 7 Dynamic Content Carousel - Carousel Transitions
  • Next Article: JavaScript Memoisation
    Next Article: JavaScript Memoisation

Blog Archives

  • December 2019 (1)
  • November 2019 (1)
  • August 2019 (1)
  • May 2019 (1)
  • October 2018 (1)
  • February 2017 (2)
  • January 2017 (3)
  • November 2016 (1)
  • July 2016 (1)
  • January 2016 (1)
More...

Categories

  • Angular
  • CSS
  • Development Environment
  • Drupal
  • Git
  • JavaScript
  • Mac
  • Programming
  • React
  • Tutorial
  • Workflow
  • Home
  • Blog
  • Sandbox
  • Pattern Library
© 2026 Alvin Pascoe
hello{at}alvinpascoe{dot}com
Made by Me, Alvin Pascoe