Skip to content

Instantly share code, notes, and snippets.

//guess where this fails.
this.x = function() {
hello();
}
(foo || bar).call();
@jhartikainen
jhartikainen / lol.js
Last active December 13, 2016 01:36
JavaScript doesn't have classes lololo
//java
class X extends Y {
public X() {
super();
}
public void method() {
}
public static staticMethod() {
@jhartikainen
jhartikainen / test.js
Last active November 25, 2016 08:43
Avoiding multiple asserts
//easy way to check if object has the expected "shape":
it('tests something', function() {
var expectedObject = {
some: 'prop',
values: 'here'
};
var result = doStuff();
assert.deepEqual(result, expectedObject);
@jhartikainen
jhartikainen / timeouts.js
Created September 5, 2016 23:50
Chained timeouts
var moves = []..
function makeMove() {
var m = moves.shift();
if(!m) {
return everythingDone();
}
setTimeout(function() {
activateButton(m);
@jhartikainen
jhartikainen / chain.js
Created September 5, 2016 23:11
Chained promises
//let's say all the moves are in this array
var moves = [...];
moves.reduce(function(p, move) {
return p.then(activateWithDelay(move.button))
.then(deactivateWithDelay(move.button));
}, Promise.resolve());
it('"moveRight()" should increment the "x" propety by 1', function () {
var blocky = new Block(15, 30);
blocky.moveRight();
assert.equal(blocky.x, 16);
});
//....vs....
it('"moveRight()" should increment the "x" propety by 1', function () {
var startingX = 15;
@jhartikainen
jhartikainen / paramTest.js
Created June 12, 2016 12:46
Parametrized test with Mocha example
describe('Something', function() {
var values = ['a', 'b', 'c'];
values.forEach(function(val) {
it('should do something with ' + val + ' in this test', function() {
assert.equal(foo(), val);
});
})
});
@jhartikainen
jhartikainen / foo.js
Last active December 4, 2016 14:04
Using angular isolated scopes as event emitters
someModule.service('something', function($rootScope) {
var emitter = $rootScope.$new(true);
var data = whateverStuffHere;
return {
onDataUpdated: function(callback) {
//by returning the result from $on, we get
//the ability to remove event listeners easily
return emitter.$on('update', callback);
@jhartikainen
jhartikainen / tests.js
Created May 13, 2016 10:59
Example of stubbing a complex object
describe('something', function() {
var oldXrm;
beforeEach(function() {
oldXrm = Xrm;
Xrm = {
Page: {
getAttribute: sinon.stub()
}
};
@jhartikainen
jhartikainen / sandbox.js
Last active March 24, 2016 14:05
Manual Sinon sandboxes
describe('something', function() {
var sandbox;
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});