Skip to content

Instantly share code, notes, and snippets.

@thillain
Last active August 29, 2015 14:07
Show Gist options
  • Save thillain/41b9addf6fd9bb9f03b2 to your computer and use it in GitHub Desktop.
Save thillain/41b9addf6fd9bb9f03b2 to your computer and use it in GitHub Desktop.
Javascript test
describe('clone object', function () {
it('should clone an object', function () {
var expected = {name: 'Ahmed', age: 27, skills: ['cycling', 'walking', 'eating']},
obj = {};
if (expected instanceof Object){
obj = expected.constructor();
for (var attr in expected) {
if (expected.hasOwnProperty(attr))
obj[attr] = expected[attr];
}
}
expect(obj).toEqual(expected);
expect(obj).not.toBe(expected);
});
});
describe('flatten array', function () {
it('should flatten an array', function () {
var arr = [1, 2, [1, 2, [3, 4, 5, [1]]], 2, [2]],
expected = [1, 1, 1, 2, 2, 2, 2, 3, 4, 5];
var flatten = function(toFlatten) {
var isArray = Object.prototype.toString.call(toFlatten) === '[object Array]';
if (isArray && toFlatten.length > 0) {
var head = toFlatten[0];
var tail = toFlatten.slice(1);
return (flatten(head).concat(flatten(tail))).sort();
} else {
return ([].concat(toFlatten)).sort();
}
};
//function onlyUnique(value, index, self) {
// return self.indexOf(value) === index;
//}
arr = flatten(arr);
//arr = arr.filter(onlyUnique);
expect(arr).toEqual(expected);
});
});
describe('scoping', function () {
it('should correctly deal with scoping `this` back to the callee', function () {
var mod = new Module(),
request;
request = function (callback) {
return callback();
};
function Module () {
this.foo = 'bar';
}
Module.prototype.method = function() {
return this.foo;
};
Module.prototype.req = function() {
return request(this.method);
};
expect(mod.req()).toBe('bar');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment