Simple Javascript Unit Testing


In this post, we have introduces the simplest way of doing unit tests in VBScript, here is the equivalent version in Javascript. With Javascript, it allows more flexible and powerful syntax. So you can throw exceptions which makes more sense when things go wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Simple Unit Tests in Javascript
var Assert = {
    IsTrue: function(x, msg) {
      if (!x) {
        throw msg;
      }
    },
    
    IsFalse: function(x, msg) {
      this.IsTrue(!x, msg);
    },
    
    AreEqual: function(a, b, msg) {
      if (a !== b) {
        throw msg;
      }
    }
}
// Simple Unit Tests in Javascript
var Assert = {
    IsTrue: function(x, msg) {
      if (!x) {
        throw msg;
      }
    },
    
    IsFalse: function(x, msg) {
      this.IsTrue(!x, msg);
    },
    
    AreEqual: function(a, b, msg) {
      if (a !== b) {
        throw msg;
      }
    }
}

You could keep adding more test methods such as AreDifferent, AreSame, IsNotNull etc. The following will fail the test, just to demonstrate the usage:

1
2
3
4
5
try {
    Assert.AreEqual(1, "1", "not equal");
} catch(e) {
    WScript.Echo(e);
}
try {
    Assert.AreEqual(1, "1", "not equal");
} catch(e) {
    WScript.Echo(e);
}

You can wrap all the tests in a JS file, and run (e.g. using cscript.exe or nodejs) the test file capture any exceptions/output.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
230 words
Last Post: Algorithms to Find Kth Largest/Smallest Element in an Array/List
Next Post: Do Thread A and B Require Mutex to Operate on High/Low of a DWORD?

The Permanent URL is: Simple Javascript Unit Testing

2 Comments

Leave a Reply