An Introduction to Unit Testing

Lea Fox
Caffeine and Testing
2 min readJan 27, 2016

Unit testing, it sounds nice, doesn’t it? But what is it? And how do you do it?

Unit testing involves making sure each of your functions take in the right arguments and return what, you, the developer, intended that function to return. That’s about the long and the short of it.

Okay, so now we know what unit testing is but, how do we do it? You’re going to want to start by selecting a testing library and an assertion library. Which one you choose doesn’t really matter. They all have the same basic functionality. I have enjoyed using mochajs and chaijs, so those are the two libraries I’ll be referencing.

Great, you’ve got your library. Let’s make a test. Unit testing began making since to me when I realized the pattern that every test follow.

You give the test a function, you pass that function some information, you check to see if the information you get back is what you’re expecting. Let me show you a basic example.

describe('GET /', function(){
it('responds with index.html', function(done){
superTest('localhost:8080')
.get('/')
.set('Accept', 'text/html')
.expect(200)
.end(function(err, res){
if (err) return done(err);
done();
});
});
});

I’m using mocha to describe what we’re testing. It sets up a context for our test. Then I use a separate module called supertest to ensure that my site send a html page when a user makes a request to the home page. What’s great about many of these libraries is that they resemble english. The methods are very descriptive and generally they do what it sounds like they do.

Unit testing can seem daunting, but at the end of the day its really just about making sure your code is doing exactly what you intend it to.

--

--