How to make your own testing framework

Although there a lot of testing frameworks out there it's not actually that difficult to write your own and it's a great way to understand how to write better unit tests. Before we get into this make sure to complete the try and catch basics.

The basic of any unit testing framework is the assert statement. This function will usually take a value and compare it to other value. If the result is true then the test passes. If the result is false then the test fails. For now we will just check if the values passed are equal (==).

var assert = function(actual, expected) {
  if(actual != expected) {
    //Run if failed
    throw {type: "Fail", details: {actual: actual, expected: expected}};
  } else {
    //Run if successful
    console.log("Success", {type: "Test passed", details: {actual: actual, expected: expected}});

//Will pass
assert(true, true);
assert("Some string", "Some string");
assert(1, 1);

//Will Fail
assert(true, false);
assert("Some string", "Some other string");
assert(2, 1);

Assertions are great but they become really useful when they are grouped together. When using a test group they will usually relate to one function in our API or app. We will be making describe function that will wrap are tests.

//test wrapper
var describe = function(message, testFunc) {
  try {
  } catch(err) {
    console.error("Failure", err);

describe("Test group", function() {
  assert(true, true);
  assert("Some string", "Some string");
  assert(1, 1);

Example of using unit tests in a simple application:

//Person Object
var Person = function(firstname, lastname, age) {
  var self = this;
  self.firstname = firstname;
  self.lastname = lastname;
  self.age = age;
  self.greeting = function() {
    return "Hello, " + self.firstname + " " + self.lastname + ". Your are " + age + " years old";

//Unit Tests
//Successful Tests
var testPerson = new Person("john","jingle",15);
describe("Should have a successful user case", function() {
  assert.equal(testPerson.firstname, "john", "First name is john");
  assert.notEqual(testPerson.lastname, "lebowski", "Last name is not lebowski");
  assert.atMost(testPerson.age, 20, "Age is at most 20");

//Failure Tests
var testPerson = new Person("terry","wright",20);
describe("Should have a failure user case", function() {
  assert.equal(testPerson.firstname, "john", "First name should not be john");
  assert.notEqual(testPerson.lastname, "wright", "Last name is ");
  assert.atMost(testPerson.age, 16, "Age is 15");