Creating unit tests without relying on a testing framework: A guide

My goal is to unit test a simple function using pure JavaScript:

NS.isType = function (type, obj) {
    if (obj.constructor && obj.constructor.name) {
        return obj.constructor.name === type;
    }
    return toString.call(obj) === '[object ' + type + ']';
};

I am eager to start practicing unit testing in JavaScript without relying on any framework. I want to grasp the concept through a hands-on example before delving into more comprehensive resources like the O'Reilly book, (2013), which covers unit testing with frameworks.

Could someone guide me on how to unit test the above method using only pure JavaScript without any external library?

Answer №1

Unit testing is like a game of red light green light.

First, you create a test outlining the expected behavior of your function. Running the test will result in failure since the function has not been implemented yet (RED).

Next, you implement the function and run the test again. This time, the test will pass as the function now behaves correctly (GREEN).

To ensure the effectiveness of your test, make slight changes to cause it to fail once more (to confirm it doesn't always pass) (RED).

Adjust the test so that it passes once again.

During unit testing, asserting plays a crucial role. Here's a simple example:

function addNumbers(A, B){
  return A + B;
}
//test suite snippet:
var tests=[];
function assertEqual(a, b, message){
  tests.push({
    pass: a === b,
    message: message
  });
}
assertEqual(addNumbers(1,2), 3, "Ensuring 1 plus 2 equals 3");
assertThrows(addNumbers("hello",7), "Passing a string as one of the parameters should trigger an error");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Inquiring about the rationale behind using `jquery.ui.all.css` specifically

I'm curious about the impact of jquery.ui.all.css on Tabs As soon as I remove it, <link rel="stylesheet" href="jquery/dev/themes/base/jquery.ui.all.css"> My tabs stop functioning. Here's my query: What exactly does the jquery.ui.all.cs ...

Using jQuery to serialize parameters for AJAX requests

I could use some help figuring out how to set up parameters for a $.ajax submission. Currently, I have multiple pairs of HTML inputs (i pairs): > <input type="hidden" value="31" name="product_id"> <input > type="hidden" value="3" name="qua ...

One way to generate div elements based on the number in an input field when a button is clicked, but ensuring it only happens once

What I am attempting to achieve is: Retrieve data from a JSON file upon button click. Display the data in separate boxes, each one different for every element of the array. For instance, if the JSON provides 3 rows of data, there should be 3 distinct box ...

Having trouble with the express message! I can't seem to access the template I created

I am looking to receive a notification similar to an alert, as described in this link: https://github.com/visionmedia/express-messages By default, I receive something like this https://i.stack.imgur.com/9XlA9.png If I use a template, I do not get any out ...

How do I make the YouTube Grid Gallery player show up in a pop-up window?

I have been experimenting with the following code: <head> <script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script> <script type="text/javascript"> function loadVideo(playerUrl, ...

Remove the class upon clicking

I recently created a toggle-menu for my website that includes some cool effects on the hamburger menu icon. The issue I am facing is that I added a JavaScript function to add a "close" class when clicking on the menu icon, transforming it into an "X". Whil ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

The absence of data in a c# web api controller is causing issues with jQuery AJAX post requests

When I am sending data to a c# web api controller, I use the following method: $.ajax({ type: "POST", url: "menuApi/menu/Cost", data: JSON.stringify(order), contentType: "application/json", success: function (data) { window.alert(&apo ...

Vue JS: Extracting both the unique ID and value from an array of input simultaneously

I am new to Vue and currently exploring its capabilities. I am experimenting with the Element UI for Vue's user interface. Specifically, I am working with the Input Number Component, to manage an array of data. Let's assume my data is structured ...

Adjust the color of the paper in Material-UI

I'm in the process of creating a React project using the material-ui library. Currently, I am facing an issue with customizing the drawer component's background color. After some research, I learned that modifying the paper attribute of the drawe ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

What is the correct way to use Deviceready in an Ionic application?

I am currently working on a mobile application built with Cordova and Ionic. The default page of the application requires the use of the SQLLite plugin. https://github.com/brodysoft/Cordova-SQLitePlugin The issue I am facing is that the view contains n ...

Uniform Image Sizes in Bootstrap Carousel (With One Exception)

I am encountering a JavaScript exception related to image size. I am trying to set a fixed size for the images in my carousel, allowing them to auto adjust or resize without concern for distortion or pixelation. I have experimented with max-width and widt ...

Tips for splitting the json_encode output in Javascript

Looking for help with extracting specific values from JSON data retrieved via PHP and AJAX. I only want to display the agent name in my ID, not the entire object that includes "name" : "Testing". Here is the console output: [{"agent_module_id":"1","agen ...

There seems to be an issue with declaring Gulp Open

Here is the code snippet for my `open.js` task: import gulp from 'gulp'; import gulpOpen from 'gulp-open'; gulp.task('open', () => { // doesn't work with `function()` either. const options = { uri: 'local ...

Utilizing Selenium Webdriver to efficiently scroll through a webpage with AJAX-loaded content

I am currently utilizing Selenium Webdriver to extract content from a webpage. The challenge I'm facing is that the page dynamically loads more content using AJAX as the user scrolls down. While I can programmatically scroll down using JavaScript, I a ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

Showcasing Portfolio Work in a User-Friendly Mobile Design

Currently revamping my portfolio website and looking for ways to optimize the display of my personal projects. I have a card-like interface in place that works well on desktop but only shows one project at a time on mobile devices. Seeking solutions to imp ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...