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

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Fiber react three selection group

I am attempting to combine/select multiple meshes as a group. Currently, my code looks like this: //wrapper <group onPointerOver={(e) => getOverEvent(e)} onPointerOut={(e) => getOutEvent(e)} onPointer ...

Explication of syntax not functioning

Following the instructions provided here but encountering issues, any assistance? <script type="text/javascript" src="sh/src/shCore.js"></script> <script type="text/javascript" src="sh/scripts/shBrushJScript.js"></script> <lin ...

Guide to swapping images on button click in HTML with dynamically changing image URLs retrieved from the server

I am a beginner in client-side scripting and new to Stack Overflow. I am looking for guidance on how to change an image within a div element upon clicking a button or anchor tag. Here is the code snippet I have written to achieve this: $scope.captchaCha ...

Consistently shifting the Aframe camera towards the focal point

Is there a way to continuously adjust the view of my Aframe scene based on the current viewing direction? It seems like there are two key components needed for this: (1) obtaining the current viewing direction in the correct format, and (2) creating and u ...

Encountered an Error: Trying to use a function that is undefined - While utilizing Jquery Tabs

Working on implementing Jquery Tabs using the "description" and "reviews" li tags as tabs. Testing it out here . Everything seems to be functioning correctly here Key Points: This is Wordpress Multi-Site setup. The issue occurs in certain folders or "si ...

In order to maintain a custom tooltip in an open state until it is hovered over, while also controlling its

When hovering over the first column of the table, a tooltip will appear. Within each material tooltip, I would like to include a button at the bottom right after the JSON data. When this button is clicked, it should open an Angular Material dialog. <ng ...

The date conversion within AngularJS's interpolation is resulting in an incorrect timestamp

Given a timestamp of 1519347000, I am trying to convert it into a date format using interpolation like so: {{$ctrl.myTimestamp | date:'MMM d y, hh:mm'}} The resulting value is Jan 18 1970, 04:02, which is incorrect. The correct date should be F ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Configuring properties for a component by retrieving data from MongoDB using an API request

My current API call utilizes axios in the following format: Service.get('path/to/api', (status, data) => { this.setState({ ComponentData: data, loaded: true}); }); {this.state.loaded && <Component id={this.state.ComponentD ...

Prevent selenium webdriver from executing parent tests

Currently, I am utilizing the selenium web driver to execute a series of tests. Within my project, I have a fundamental class that encompasses numerous tests. The second class in my project is named 'People' and includes an additional set of te ...

Is it possible to exclusively focus on the specified data attributes?

Is there a method to specifically target the 'data-season' attribute with the value "winter"? This is my HTML: <li data-season="summer">summer <ul class="groups"> <li data-item="beach">beach</li> <li data-item ...

Having trouble getting Three.js JSON models to cast shadows properly?

Recently, I've been experimenting with blender exported models in Three.js. I have successfully imported a model and observed how light interacts with the object. While a directionalLight is illuminating the front-facing parts, I'm facing an issu ...

No change in the element's text content when clicking

I'm working on creating a timer that counts down from either 15 or 30 seconds. However, I'm having trouble changing the text value when the 15 button is clicked. Can someone help me figure out what's wrong? Thank you in advance HTML <h ...

Submitting form data using Vue and PHPMailer

I've been encountering an issue with submitting a contact form from a page. After submitting the form, nothing seems to happen. My tech stack includes Vue, Axios, and PHPMailer for handling this functionality. Upon inspecting the network tab, it appea ...

Create a JSON array from a collection using Backbone.js

I have a collection called Platforms in my backbone framework. The structure of this Platforms collection is organized as follows: Platforms PlatformList models 0: Platform attributes id: 1 name: "some name" 1 ...

Encountering an undefined variable in the .env file

Once the .env file was created in the main React folder REACT_APP_API_KEY=gzomlK5CKLiaIWS.... I also installed the .env NPM library Despite this, I continued to receive undefined in the API file. What could be causing this issue? import React, { useState ...

The event is being triggered on two separate occasions

Hey there! I'm trying to bind the onclick event to both a parent and child element using the same method. However, I'm running into an issue where the event is being fired twice. Any suggestions on how to prevent this from happening? <div id= ...

What is the process for creating URL query parameters?

What is the process for generating parameters after node?_=xxxxxx? If I am using a Python script to access the URL, how can I retrieve these parameters? edit: I apologize for not providing enough information. This is my first post as a novice. I am atte ...

The first name of the user is not shown following the completion of the registration

I'm currently developing an application using React and Node.js. In the frontend, I have implemented a functionality where upon logging in, users are redirected from the /login route to the root route and greeted with their first name. However, when a ...