简体   繁体   中英

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM