This website wants to use persistent Cookies to analyze traffic. More info.
That's FineNot OK

What would Jesus Developer do?

...using developer approach in digital analytics practice

Presentation for MeasureCamp Czechia 2018 by @cataLuc

Presentation

#1 Local development

#2 Version control

#3 Modular programming (with TDD Demo)

npm init
  • Resulting package.json:
{
  "name": "myPackage",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "ja@lukascech.cz",
  "license": "ISC"
}
  • Install Mocha, Chai, supporting modules:
npm install --save-dev mocha chai
npm install fs --save-dev
npm install vm --save-dev
  • Update your package.json with test framework configuration:
{
  "name": "myPackage",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "mocha"
  }
  "author": "ja@lukascech.cz",
  "license": "ISC",
  "devDependencies": {
    "chai": "^4.1.2",
    "fs": "0.0.1-security",
    "mocha": "^5.2.0",
    "vm": "^0.1.0"
  }
}
  • Create getCurrentTimestamp.js file like a hacker:
mkdir src
cd src
touch getCurrentTimestamp.js
  • Create another file for your tests:
cd ..
mkdir test
cd test
touch test.js
  • Edit test.js and write a test for what getCurrentTimestamp.js should do:
var fs = require("fs");
const vm = require('vm');
var expect = require('chai').expect;

describe('My Test Suite', function () {

  var path = './src/getCurrentTimestamp.js';
  vm.runInThisContext(fs.readFileSync(path, 'utf-8'), path);
  it('getCurrentTimestamp() should return timestamp in ISO format', function () {

    // 1. ARRANGE

    // 2. ACT
    var currentTimestamp = getCurrentTimestamp();
    console.log('returned timestamp: ' + currentTimestamp);

    // 3. ASSERT
    expect(currentTimestamp).to.match(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/);

  });
});
  • Run the test to test that the test fails :wink::
cd ..
npm test
  • Write the getCurrentTimestamp.js code:
function getCurrentTimestamp() {
  // Get local time as ISO string with offset at the end
  var now = new Date();
  var tzo = -now.getTimezoneOffset();
  var dif = tzo >= 0 ? '+' : '-';
  var pad = function(num) {
      var norm = Math.abs(Math.floor(num));
      return (norm < 10 ? '0' : '') + norm;
  };
  return now.getFullYear() 
      + '-' + pad(now.getMonth()+1)
      + '-' + pad(now.getDate())
      + 'T' + pad(now.getHours())
      + ':' + pad(now.getMinutes()) 
      + ':' + pad(now.getSeconds())
      + '.' + pad(now.getMilliseconds())
      + dif + pad(tzo / 60) 
      + ':' + pad(tzo % 60);
}
  • See that the test passes now:
cd ..
npm test
  • Celebrate, refactor happily ever after...

#4 API-based approach

...to be continued