Test Driven Development 101 and JS testing

leanminmachine

leanminmachine

Posted on July 14, 2018

Test Driven Development 101 and JS testing

Test Driven Development Cycle

TDD Cycle:

  1. Write a test case which will obviously fail in the beginning. Do not have more than one failing test case at a time. Implement the simplest algorithm first, then generalise it when you identify some patterns.
  2. Write code that makes test case pass
  3. Refactor code on code base. Do not refactor when your tests are failing. Make test cases pass first.

I’m honestly still trying to get the hang of testing and I am still trying to familiarise myself with js in general.

Writing tests in Jest

Setting up is pretty straightforward.
Just npm install jest.
Remember to change in package.json,

  "scripts": {
    "test": "jest"
  },
Enter fullscreen mode Exit fullscreen mode

Name test file [file name].test.js
First, we write our test.
The test would require the main module.
We can assign it to a variable name.
For example:

const arabicToRomanNumbers = require(“./arabicToRomanNumbers”); 
Enter fullscreen mode Exit fullscreen mode

Following that, we can start writing our test.

The first test would be something like,

test(“I is 1”, () => {
expect(arabicToRomanNumbers(“I”)).toBe(1);
});
Enter fullscreen mode Exit fullscreen mode

Name file name [file name].js
Main js file: Just write the function.

function arabicNumber(string) {
if (string == “1”) {
return 1;
}

export.modules = arabicNumber;
Enter fullscreen mode Exit fullscreen mode

BTW: export class MyClass doesn’t work for nodejs. I have to use the module.exports keyword :( Or use babel npm package to transpire ES6 into commons target.

You can write all your function declarations first and then export them in an object:

function bar() {
   //bar
}

function foo() {
   //foo
}

module.exports = {
    foo: foo,
    bar: bar
};
Enter fullscreen mode Exit fullscreen mode

There's no magical one-liner though, you need to explicitly export the functions you want to be public.

var exported = {
   someFunction: function() { },
   anotherFunction: function() { },
}

module.exports = exported;
Enter fullscreen mode Exit fullscreen mode

Writing tests in mocha:

Somehow, I have to name my test file test.js. Not sure why yet.

Need to also declare assert.
const assert = require('assert');

Otherwise, the structure is pretty similar.
Write a function, and then use the function during the test itself.

describe('romanise', () => {
    it('should be less than 4000', function () {
        const result = romanise(4000);
        assert.equal(result, 'invalid input');
    });

// write more it and asserts here.

});
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
leanminmachine
leanminmachine

Posted on July 14, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related