Testing With Jasmine

This post should be a short one because testing pure functions is a simple affair.

Just as a reminder, a pure function is a function that has only explicit inputs and outputs, meaning the only things outside of itself it depends on is it's argument list and the only thing it does with any lasting effect is return a value.

Naturally, this means that when we test it we don't have to consider outside application state.

Let's start with an example. Here's about the simplest module I can think of:

module.exports = (a, b) => a + b  

If you want to follow along, create a new Node project and save this line of code as add.js.

Now it's time to grab a testing framework. You've got a few choices of what framework to use but Jasmine should work just fine.

npm install -g jasmine  

Now, from your project's root directory, run

jasmine init  

This should setup your project so you can start writing Jasmine tests. Go to the newly-made spec folder create the following file in it:

describe('add', () => {  
    var add = require('../add.js')

    it('should return the sum of its two arguments',
        () => expect(add(1, 1)).toEqual(2))
})

Save it as add_spec.js. (The _spec suffix is what tells Jasmine this is a test file.)

Go back to the root directory of your project and run

jasmine  

You should get something like the following output:

Started  
.


1 spec, 0 failures  
Finished in 0.006 seconds  

There is more to Jasmine. For example, if you look at the documentation you'll see that there are functions like beforeEach and afterEach that you can use to simulate expected application state.

But if you write functional code you won't need to do this as much, certainly not for any pure functions you write. :)

Looking for a software developer?