Test Driven Development 101 and JS testing
leanminmachine
Posted on July 14, 2018
Test Driven Development Cycle
TDD Cycle:
- 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.
- Write code that makes test case pass
- 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"
},
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”);
Following that, we can start writing our test.
The first test would be something like,
test(“I is 1”, () => {
expect(arabicToRomanNumbers(“I”)).toBe(1);
});
Name file name [file name].js
Main js file: Just write the function.
function arabicNumber(string) {
if (string == “1”) {
return 1;
}
export.modules = arabicNumber;
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
};
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;
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.
});
Posted on July 14, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.