...using developer approach in digital analytics practice
Presentation for MeasureCamp Czechia 2018 by @cataLuc
Fully-fledged IDEs
Code editors
Old-days VCS
Present-day VCS
npm init
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"
}
npm install --save-dev mocha chai
npm install fs --save-dev
npm install vm --save-dev
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"
}
}
getCurrentTimestamp.js
file like a hacker:mkdir src
cd src
touch getCurrentTimestamp.js
cd ..
mkdir test
cd test
touch test.js
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)/);
});
});
cd ..
npm test
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);
}
cd ..
npm test
...to be continued