user1637281
user1637281

Reputation:

How to write a unit test w/ out a framework?

Using pure JavaScript I want to unit test this basic function:

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

I want to start unit testing my code and I want to do it in JavaScript w/ out a framework. More importantly I want to understand the concept of unit testing w/ a small example w/ out reading an entire book. Later I plan on reading this new O'Reilly book, (2013), which focuses on unit testing using frameworks.

How can I Unit test above method using only JavaScript w/ out library?

Upvotes: 0

Views: 82

Answers (1)

HMR
HMR

Reputation: 39270

In short unit testing is about red green red green

First you write a test of what you expect your function would do. When you run the test it'll fail because you have not yet implemented it yet (RED)

Now you implement it in your funciton and run the test again, now the test will pass (GREEN).

Now you change a bit in your test again making sure it'll fail again (just to check if your test doesn't pass all the time) (RED)

Change it back so it'll pass.

You will use assert a lot, here is a small example:

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

Upvotes: 1

Related Questions