Final fixes, all tests running

This commit is contained in:
Angelos Chalaris
2018-06-18 20:41:57 +03:00
parent 977adb1198
commit e9594e6355
49 changed files with 2189 additions and 1198 deletions

70
package-lock.json generated
View File

@ -5137,6 +5137,48 @@
"pretty-format": "23.0.1" "pretty-format": "23.0.1"
} }
}, },
"jest-tap-reporter": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/jest-tap-reporter/-/jest-tap-reporter-1.9.0.tgz",
"integrity": "sha512-KBNkyWWDO0sGc593H04+QJuMHm9WEwe/0RnMD5ke2spA7nNMQao3ktU34brfOBKk7vNn5EbGIr2pODxNQo+bNA==",
"dev": true,
"requires": {
"@babel/code-frame": "7.0.0-beta.36",
"chalk": "2.4.1",
"string.prototype.padend": "3.0.0",
"string.prototype.padstart": "3.0.0",
"strip-ansi": "4.0.0",
"utf8-bar": "0.1.0"
},
"dependencies": {
"@babel/code-frame": {
"version": "7.0.0-beta.36",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.0.0-beta.36.tgz",
"integrity": "sha512-sW77BFwJ48YvQp3Gzz5xtAUiXuYOL2aMJKDwiaY3OcvdqBFurtYfOpSa4QrNyDxmOGRFSYzUpabU2m9QrlWE7w==",
"dev": true,
"requires": {
"chalk": "2.4.1",
"esutils": "2.0.2",
"js-tokens": "3.0.2"
}
},
"ansi-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz",
"integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=",
"dev": true
},
"strip-ansi": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz",
"integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=",
"dev": true,
"requires": {
"ansi-regex": "3.0.0"
}
}
}
},
"jest-util": { "jest-util": {
"version": "23.1.0", "version": "23.1.0",
"resolved": "https://registry.npmjs.org/jest-util/-/jest-util-23.1.0.tgz", "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-23.1.0.tgz",
@ -7684,6 +7726,28 @@
} }
} }
}, },
"string.prototype.padend": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/string.prototype.padend/-/string.prototype.padend-3.0.0.tgz",
"integrity": "sha1-86rvfBcZ8XDF6rHDK/eA2W4h8vA=",
"dev": true,
"requires": {
"define-properties": "1.1.2",
"es-abstract": "1.11.0",
"function-bind": "1.1.1"
}
},
"string.prototype.padstart": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/string.prototype.padstart/-/string.prototype.padstart-3.0.0.tgz",
"integrity": "sha1-W8+tOfRkm7LQMSkuGbzwtRDUskI=",
"dev": true,
"requires": {
"define-properties": "1.1.2",
"es-abstract": "1.11.0",
"function-bind": "1.1.1"
}
},
"string.prototype.trim": { "string.prototype.trim": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz", "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz",
@ -8242,6 +8306,12 @@
} }
} }
}, },
"utf8-bar": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/utf8-bar/-/utf8-bar-0.1.0.tgz",
"integrity": "sha512-AU+KwhlIChF/Su3d/tBrnhtDS6Bd1YWXeRc/If2/XEV/3f8LTSGJQQVONqUI6fwwTrkT5GKbdYxm7qQD7nEcCQ==",
"dev": true
},
"util-deprecate": { "util-deprecate": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",

View File

@ -5,6 +5,7 @@
"fs-extra": "^6.0.0", "fs-extra": "^6.0.0",
"html-minifier": "^3.5.15", "html-minifier": "^3.5.15",
"jest": "^23.1.0", "jest": "^23.1.0",
"jest-tap-reporter": "^1.9.0",
"jsdom": "^11.10.0", "jsdom": "^11.10.0",
"markdown-it": "^8.4.1", "markdown-it": "^8.4.1",
"mini.css": "^2.3.7", "mini.css": "^2.3.7",
@ -16,8 +17,6 @@
"rollup-plugin-babel": "^3.0.4", "rollup-plugin-babel": "^3.0.4",
"rollup-plugin-babel-minify": "^4.0.0", "rollup-plugin-babel-minify": "^4.0.0",
"semistandard": "^12.0.1", "semistandard": "^12.0.1",
"tap-spec": "^4.1.1",
"tape": "^4.9.0"
}, },
"name": "30-seconds-of-code", "name": "30-seconds-of-code",
"description": "A collection of useful JavaScript snippets.", "description": "A collection of useful JavaScript snippets.",
@ -33,8 +32,7 @@
"extractor": "node ./scripts/extract.js", "extractor": "node ./scripts/extract.js",
"packager": "node ./scripts/module.js", "packager": "node ./scripts/module.js",
"localizer": "node ./scripts/localize.js", "localizer": "node ./scripts/localize.js",
"testold": "tape test/**/*.test.js | tap-spec", "test": "jest --verbose"
"test": "jest test/**/*.test.js"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -51,5 +49,14 @@
"url": "https://github.com/Chalarangelo/30-seconds-of-code/issues" "url": "https://github.com/Chalarangelo/30-seconds-of-code/issues"
}, },
"homepage": "https://github.com/Chalarangelo/30-seconds-of-code#readme", "homepage": "https://github.com/Chalarangelo/30-seconds-of-code#readme",
"dependencies": {} "dependencies": {},
"jest": {
"reporters": [
["jest-tap-reporter", {
"logLevel": "INFO",
"showInternalStackTraces": false,
"filePath": "test/testlog"
}]
]
}
} }

View File

@ -84,7 +84,7 @@ snippetFiles
}); });
try { try {
fs.writeFileSync(path.join(TEST_PATH,'testlog'),`Test log for: ${new Date().toString()}\n`); fs.writeFileSync(path.join(TEST_PATH,'testlog'),`Test log for: ${new Date().toString()}\n`);
child_process.execSync(`npm test >> ${TEST_PATH}/testlog`); child_process.execSync(`npm test`);
} }
catch (e) { catch (e) {
fs.appendFileSync(path.join(TEST_PATH,'testlog')); fs.appendFileSync(path.join(TEST_PATH,'testlog'));

View File

@ -5,5 +5,5 @@ test('call is a Function', () => {
expect(call).toBeInstanceOf(Function); expect(call).toBeInstanceOf(Function);
}); });
test('Calls function on given object', () => { test('Calls function on given object', () => {
expect(call('map', x => x * 2)([1, 2, 3])).toBe([2, 4, 6]); expect(call('map', x => x * 2)([1, 2, 3])).toEqual([2, 4, 6]);
}); });

View File

@ -8,7 +8,7 @@ test('Capitalizes the first letter of a string', () => {
expect(capitalize('fooBar')).toBe('FooBar'); expect(capitalize('fooBar')).toBe('FooBar');
}); });
test('Capitalizes the first letter of a string', () => { test('Capitalizes the first letter of a string', () => {
expect(capitalize('fooBar', true)).toBe('FooBar'); expect(capitalize('fooBar', true)).toBe('Foobar');
}); });
test('Works with characters', () => { test('Works with characters', () => {
expect(capitalize('#!#', true)).toBe('#!#'); expect(capitalize('#!#', true)).toBe('#!#');

View File

@ -5,7 +5,7 @@ test('capitalizeEveryWord is a Function', () => {
expect(capitalizeEveryWord).toBeInstanceOf(Function); expect(capitalizeEveryWord).toBeInstanceOf(Function);
}); });
test('Capitalizes the first letter of every word in a string', () => { test('Capitalizes the first letter of every word in a string', () => {
expect(capitalizeEveryWord('hello world!'), 'Hello World!').toBe(); expect(capitalizeEveryWord('hello world!')).toBe('Hello World!');
}); });
test('Works with characters', () => { test('Works with characters', () => {
expect(capitalizeEveryWord('$# @!')).toBe('$# @!'); expect(capitalizeEveryWord('$# @!')).toBe('$# @!');

View File

@ -5,7 +5,7 @@ test('chunk is a Function', () => {
expect(chunk).toBeInstanceOf(Function); expect(chunk).toBeInstanceOf(Function);
}); });
test('chunk([1, 2, 3, 4, 5], 2) returns [[1,2],[3,4],[5]] ', () => { test('chunk([1, 2, 3, 4, 5], 2) returns [[1,2],[3,4],[5]] ', () => {
expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1,2],[3,4][5]]); expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1,2],[3,4],[5]]);
}); });
test('chunk([]) returns []', () => { test('chunk([]) returns []', () => {
expect(chunk([])).toEqual([]) expect(chunk([])).toEqual([])
@ -20,13 +20,13 @@ test('chunk(string, 2) returns [ st, ri, ng ]', () => {
expect(chunk('string', 2)).toEqual( [ 'st', 'ri', 'ng' ]) expect(chunk('string', 2)).toEqual( [ 'st', 'ri', 'ng' ])
}); });
test('chunk() throws an error', () => { test('chunk() throws an error', () => {
expect(chunk()).toThrow(); expect(() => {chunk();}).toThrow();
}); });
test('chunk(undefined) throws an error', () => { test('chunk(undefined) throws an error', () => {
expect(chunk(undefined)).toThrow(); expect(() => {chunk(undefined);}).toThrow();
}); });
test('chunk(null) throws an error', () => { test('chunk(null) throws an error', () => {
expect(chunk(null)).toThrow(); expect(() => {chunk(null);}).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
chunk('This is a string', 2); chunk('This is a string', 2);

View File

@ -6,5 +6,5 @@ test('cloneRegExp is a Function', () => {
}); });
const rgTest = /./g; const rgTest = /./g;
test('Clones regular expressions properly', () => { test('Clones regular expressions properly', () => {
expect(cloneRegExp(rgTest).not.toEqual(rgTest); expect(cloneRegExp(rgTest)).not.toBe(rgTest);
}); });

View File

@ -9,14 +9,14 @@ const b = deepClone(a);
const c = [{foo: "bar"}]; const c = [{foo: "bar"}];
const d = deepClone(c); const d = deepClone(c);
test('Shallow cloning works', () => { test('Shallow cloning works', () => {
expect(a).not.toEqual(b); expect(a).not.toBe(b);
}); });
test('Deep cloning works', () => { test('Deep cloning works', () => {
expect(a.obj).not.toEqual(b.obj); expect(a.obj).not.toBe(b.obj);
}); });
test('Array shallow cloning works', () => { test('Array shallow cloning works', () => {
expect(c).not.toEqual(d); expect(c).not.toBe(d);
}); });
test('Array deep cloning works', () => { test('Array deep cloning works', () => {
expect(c[0]).not.toEqual(d[0]); expect(c[0]).not.toBe(d[0]);
}); });

View File

@ -5,5 +5,5 @@ test('defaults is a Function', () => {
expect(defaults).toBeInstanceOf(Function); expect(defaults).toBeInstanceOf(Function);
}); });
test('Assigns default values for undefined properties', () => { test('Assigns default values for undefined properties', () => {
expect(defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 })).toBe({ a: 1, b: 2 }); expect(defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 })).toEqual({ a: 1, b: 2 });
}); });

View File

@ -8,7 +8,7 @@ test('Standard 1v1s', () => {
expect(elo([1200, 1200])).toEqual([1216,1184]); expect(elo([1200, 1200])).toEqual([1216,1184]);
}); });
test('Standard 1v1s' ,() => { test('Standard 1v1s' ,() => {
expect(elo([1200, 1200], 64)).toBe([1232, 1168]); expect(elo([1200, 1200], 64)).toEqual([1232, 1168]);
}); });
test('4 player FFA, all same rank', () => { test('4 player FFA, all same rank', () => {
expect(elo([1200, 1200, 1200, 1200]).map(Math.round)).toEqual([1246, 1215, 1185, 1154]); expect(elo([1200, 1200, 1200, 1200]).map(Math.round)).toEqual([1246, 1215, 1185, 1154]);

View File

@ -4,7 +4,7 @@ const equals = require('./equals.js');
test('equals is a Function', () => { test('equals is a Function', () => {
expect(equals).toBeInstanceOf(Function); expect(equals).toBeInstanceOf(Function);
}); });
test('{ a: [2, {e: 3}], b: [4], c: 'foo' } is equal to { a: [2, {e: 3}], b: [4], c: 'foo' }', () => { test('{ a: [2, {e: 3}], b: [4], c: \'foo\' } is equal to { a: [2, {e: 3}], b: [4], c: \'foo\' }', () => {
expect(equals({ a: [2, {e: 3}], b: [4], c: 'foo' }, { a: [2, {e: 3}], b: [4], c: 'foo' })).toBeTruthy(); expect(equals({ a: [2, {e: 3}], b: [4], c: 'foo' }, { a: [2, {e: 3}], b: [4], c: 'foo' })).toBeTruthy();
}); });
test('[1,2,3] is equal to [1,2,3]', () => { test('[1,2,3] is equal to [1,2,3]', () => {

View File

@ -11,5 +11,5 @@ test('Returns the appropriate key', () => {
fred: { age: 40, active: false }, fred: { age: 40, active: false },
pebbles: { age: 1, active: true } pebbles: { age: 1, active: true }
}, },
o => o['active']).toBe('barney'); o => o['active'])).toBe('barney');
}); });

View File

@ -11,5 +11,5 @@ test('eturns the appropriate key', () => {
fred: { age: 40, active: false }, fred: { age: 40, active: false },
pebbles: { age: 1, active: true } pebbles: { age: 1, active: true }
}, },
o => o['active']).toBe('pebbles'); o => o['active'])).toBe('pebbles');
}); });

View File

@ -1,23 +1,18 @@
const expect = require('expect'); const expect = require('expect');
let output = ''; let output = '';
const console = {}; const functionName = fn => fn.name;
console.debug = (x) => output = x;
const functionName = fn => (console.debug(fn.name), fn);
test('functionName is a Function', () => { test('functionName is a Function', () => {
expect(functionName).toBeInstanceOf(Function); expect(functionName).toBeInstanceOf(Function);
}); });
functionName(Math.max);
test('Works for native functions', () => { test('Works for native functions', () => {
expect(output).toBe('max'); expect(functionName(Math.max)).toBe('max');
}); });
function fun(x) {return x;} function fun(x) {return x;}
functionName(fun);
test('Works for functions', () => { test('Works for functions', () => {
expect(output).toBe('fun'); expect(functionName(fun)).toBe('fun');
}); });
const fn = x => x; const fn = x => x;
functionName(fn);
test('Works for arrow functions', () => { test('Works for arrow functions', () => {
expect(output).toBe('fn'); expect(functionName(fn)).toBe('fn');
}); });

View File

@ -10,7 +10,7 @@ function Foo() {
} }
Foo.prototype.c = () => 3; Foo.prototype.c = () => 3;
test('Returns own methods', () => { test('Returns own methods', () => {
expect(functions(new Foo()).toEqual( ['a', 'b']); expect(functions(new Foo())).toEqual( ['a', 'b']);
}); });
test('Returns own and inherited methods', () => { test('Returns own and inherited methods', () => {
expect(functions(new Foo(), true)).toEqual(['a', 'b', 'c']); expect(functions(new Foo(), true)).toEqual(['a', 'b', 'c']);

View File

@ -5,5 +5,5 @@ test('getURLParameters is a Function', () => {
expect(getURLParameters).toBeInstanceOf(Function); expect(getURLParameters).toBeInstanceOf(Function);
}); });
test('Returns an object containing the parameters of the current URL', () => { test('Returns an object containing the parameters of the current URL', () => {
expect(getURLParameters(getURLParameters('http://url.com/page?name=Adam&surname=Smith')).toEqual({name: 'Adam', surname: 'Smith'}); expect(getURLParameters('http://url.com/page?name=Adam&surname=Smith')).toEqual({name: 'Adam', surname: 'Smith'});
}); });

View File

@ -17,13 +17,13 @@ test('head(String) returns S', () => {
expect(head('String')).toBe('S'); expect(head('String')).toBe('S');
}); });
test('head(null) throws an Error', () => { test('head(null) throws an Error', () => {
expect(head(null)).toThrow(); expect(() => { head(null); }).toThrow();
}); });
test('head(undefined) throws an Error', () => { test('head(undefined) throws an Error', () => {
expect(head(undefined)).toThrow(); expect(() => { head(undefined); }).toThrow();
}); });
test('head() throws an Error', () => { test('head() throws an Error', () => {
expect(head()).toThrow(); expect(() => { head(); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]); head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]);

View File

@ -1,541 +1,6 @@
const expect = require('expect'); const expect = require('expect');
const httpGet = (url, callback, err = console.error) => { const httpGet = require('./httpGet.js');
const request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send();
};
test('httpGet is a Function', () => { test('httpGet is a Function', () => {
expect(httpGet).toBeInstanceOf(Function); expect(httpGet).toBeInstanceOf(Function);
}); });
test('Sends a GET request', () => {
httpGet('https://jsonplaceholder.typicode.com/posts/1', response => {
expect(JSON.parse(response)),toEqual({
userId: 1,
id: 1,
title:
'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
body:
'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto',
});
});
var Url = require("url");
var spawn = require("child_process").spawn;
var fs = require("fs");
XMLHttpRequest = function() {
"use strict";
/**
* Private variables
*/
var self = this;
var http = require("http");
var https = require("https");
var request;
var response;
var settings = {};
var disableHeaderCheck = false;
var defaultHeaders = {
"User-Agent": "node-XMLHttpRequest",
"Accept": "*/*",
};
var headers = {};
var headersCase = {};
var forbiddenRequestHeaders = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"content-transfer-encoding",
"cookie",
"cookie2",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via"
];
var forbiddenRequestMethods = [
"TRACE",
"TRACK",
"CONNECT"
];
var sendFlag = false;
var errorFlag = false;
var listeners = {};
/**
* Constants
*/
this.UNSENT = 0;
this.OPENED = 1;
this.HEADERS_RECEIVED = 2;
this.LOADING = 3;
this.DONE = 4;
/**
* Public vars
*/
this.readyState = this.UNSENT;
this.onreadystatechange = null;
this.responseText = "";
this.responseXML = "";
this.status = null;
this.statusText = null;
this.withCredentials = false;
/**
* Private methods
*/
/**
* Check if the specified header is allowed.
*
* @param string header Header to validate
* @return boolean False if not allowed, otherwise true
*/
var isAllowedHttpHeader = function(header) {
return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
};
/**
* Check if the specified method is allowed.
*
* @param string method Request method to validate
* @return boolean False if not allowed, otherwise true
*/
var isAllowedHttpMethod = function(method) {
return (method && forbiddenRequestMethods.indexOf(method) === -1);
};
/**
* Public methods
*/
/**
* Open the connection. Currently supports local server requests.
*
* @param string method Connection method (eg GET, POST)
* @param string url URL for the connection.
* @param boolean async Asynchronous connection. Default is true.
* @param string user Username for basic authentication (optional)
* @param string password Password for basic authentication (optional)
*/
this.open = function(method, url, async, user, password) {
this.abort();
errorFlag = false;
if (!isAllowedHttpMethod(method)) {
throw new Error("SecurityError: Request method not allowed");
}
settings = {
"method": method,
"url": url.toString(),
"async": (typeof async !== "boolean" ? true : async),
"user": user || null,
"password": password || null
};
setState(this.OPENED);
};
/**
* Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
* This does not conform to the W3C spec.
*
* @param boolean state Enable or disable header checking.
*/
this.setDisableHeaderCheck = function(state) {
disableHeaderCheck = state;
};
/**
* Sets a header for the request or appends the value if one is already set.
*
* @param string header Header name
* @param string value Header value
*/
this.setRequestHeader = function(header, value) {
if (this.readyState !== this.OPENED) {
throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
}
if (!isAllowedHttpHeader(header)) {
console.warn("Refused to set unsafe header \"" + header + "\"");
return;
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send flag is true");
}
header = headersCase[header.toLowerCase()] || header;
headersCase[header.toLowerCase()] = header;
headers[header] = headers[header] ? headers[header] + ', ' + value : value;
};
/**
* Gets a header from the server response.
*
* @param string header Name of header to get.
* @return string Text of the header or null if it doesn't exist.
*/
this.getResponseHeader = function(header) {
if (typeof header === "string"
&& this.readyState > this.OPENED
&& response
&& response.headers
&& response.headers[header.toLowerCase()]
&& !errorFlag
) {
return response.headers[header.toLowerCase()];
}
return null;
};
/**
* Gets all the response headers.
*
* @return string A string with all response headers separated by CR+LF
*/
this.getAllResponseHeaders = function() {
if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
return "";
}
var result = "";
for (var i in response.headers) {
if (i !== "set-cookie" && i !== "set-cookie2") {
result += i + ": " + response.headers[i] + "\r\n";
}
}
return result.substr(0, result.length - 2);
};
/**
* Gets a request header
*
* @param string name Name of header to get
* @return string Returns the request header or empty string if not set
*/
this.getRequestHeader = function(name) {
if (typeof name === "string" && headersCase[name.toLowerCase()]) {
return headers[headersCase[name.toLowerCase()]];
}
return "";
};
/**
* Sends the request to the server.
*
* @param string data Optional data to send as request body.
*/
this.send = function(data) {
if (this.readyState !== this.OPENED) {
throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send has already been called");
}
var ssl = false, local = false;
var url = Url.parse(settings.url);
var host;
switch (url.protocol) {
case "https:":
ssl = true;
case "http:":
host = url.hostname;
break;
case "file:":
local = true;
break;
case undefined:
case null:
case "":
host = "localhost";
break;
default:
throw new Error("Protocol not supported.");
}
if (local) {
if (settings.method !== "GET") {
throw new Error("XMLHttpRequest: Only GET method is supported");
}
if (settings.async) {
fs.readFile(url.pathname, "utf8", function(error, data) {
if (error) {
self.handleError(error);
} else {
self.status = 200;
self.responseText = data;
setState(self.DONE);
}
} else {
try {
this.responseText = fs.readFileSync(url.pathname, "utf8");
this.status = 200;
setState(self.DONE);
} catch(e) {
this.handleError(e);
}
}
return;
}
var port = url.port || (ssl ? 443 : 80);
var uri = url.pathname + (url.search ? url.search : "");
for (var name in defaultHeaders) {
if (!headersCase[name.toLowerCase()]) {
headers[name] = defaultHeaders[name];
}
}
headers.Host = host;
if (!((ssl && port === 443) || port === 80)) {
headers.Host += ":" + url.port;
}
if (settings.user) {
if (typeof settings.password === "undefined") {
settings.password = "";
}
var authBuf = new Buffer(settings.user + ":" + settings.password);
headers.Authorization = "Basic " + authBuf.toString("base64");
}
if (settings.method === "GET" || settings.method === "HEAD") {
data = null;
} else if (data) {
headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
if (!headers["Content-Type"]) {
headers["Content-Type"] = "text/plain;charset=UTF-8";
}
} else if (settings.method === "POST") {
headers["Content-Length"] = 0;
}
var options = {
host: host,
port: port,
path: uri,
method: settings.method,
headers: headers,
agent: false,
withCredentials: self.withCredentials
};
errorFlag = false;
if (settings.async) {
var doRequest = ssl ? https.request : http.request;
sendFlag = true;
self.dispatchEvent("readystatechange");
var responseHandler = function responseHandler(resp) {
response = resp;
if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
settings.url = response.headers.location;
var url = Url.parse(settings.url);
host = url.hostname;
var newOptions = {
hostname: url.hostname,
port: url.port,
path: url.path,
method: response.statusCode === 303 ? "GET" : settings.method,
headers: headers,
withCredentials: self.withCredentials
};
request = doRequest(newOptions, responseHandler).on("error", errorHandler);
reques
return;
}
response.setEncoding("utf8");
setState(self.HEADERS_RECEIVED);
self.status = response.statusCode;
response.on("data", function(chunk) {
if (chunk) {
self.responseText += chunk;
}
if (sendFlag) {
setState(self.LOADING);
}
response.on("end", function() {
if (sendFlag) {
setState(self.DONE);
sendFlag = false;
}
response.on("error", function(error) {
self.handleError(error);
};
var errorHandler = function errorHandler(error) {
self.handleError(error);
};
request = doRequest(options, responseHandler).on("error", errorHandler);
if (data) {
request.write(data);
}
reques
self.dispatchEvent("loadstart");
} else {
var contentFile = ".node-xmlhttprequest-content-" + process.pid;
var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
fs.writeFileSync(syncFile, "", "utf8");
var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
+ "var doRequest = http" + (ssl ? "s" : "") + ".request;"
+ "var options = " + JSON.stringify(options) + ";"
+ "var responseText = '';"
+ "var req = doRequest(options, function(response) {"
+ "response.setEncoding('utf8');"
+ "response.on('data', function(chunk) {"
+ " responseText += chunk;"
+ ""
+ "response.on('end', function() {"
+ "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');"
+ "fs.unlinkSync('" + syncFile + "');"
+ ""
+ "response.on('error', function(error) {"
+ "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
+ "fs.unlinkSync('" + syncFile + "');"
+ ""
+ "}).on('error', function(error) {"
+ "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
+ "fs.unlinkSync('" + syncFile + "');"
+ ""
+ (data ? "req.write('" + JSON.stringify(data).slice(1,-1).replace(/'/g, "\\'") + "');":"")
+ "req.end();";
var syncProc = spawn(process.argv[0], ["-e", execString]);
while(fs.existsSync(syncFile)) {
}
var resp = JSON.parse(fs.readFileSync(contentFile, 'utf8'));
syncProc.stdin.end();
fs.unlinkSync(contentFile);
if (resp.err) {
self.handleError(resp.err);
} else {
response = resp.data;
self.status = resp.data.statusCode;
self.responseText = resp.data.text;
setState(self.DONE);
}
}
};
/**
* Called when an error is encountered to deal with it.
*/
this.handleError = function(error) {
this.status = 0;
this.statusText = error;
this.responseText = error.stack;
errorFlag = true;
setState(this.DONE);
this.dispatchEvent('error');
};
/**
* Aborts a request.
*/
this.abort = function() {
if (request) {
request.abort();
request = null;
}
headers = defaultHeaders;
this.status = 0;
this.responseText = "";
this.responseXML = "";
errorFlag = true;
if (this.readyState !== this.UNSENT
&& (this.readyState !== this.OPENED || sendFlag)
&& this.readyState !== this.DONE) {
sendFlag = false;
setState(this.DONE);
}
this.readyState = this.UNSENT;
this.dispatchEvent('abort');
};
/**
* Adds an event listener. Preferred method of binding to events.
*/
this.addEventListener = function(event, callback) {
if (!(event in listeners)) {
listeners[event] = [];
}
listeners[event].push(callback);
};
/**
* Remove an event callback that has already been bound.
* Only works on the matching funciton, cannot be a copy.
*/
this.removeEventListener = function(event, callback) {
if (event in listeners) {
listeners[event] = listeners[event].filter(function(ev) {
return ev !== callback;
}
};
/**
* Dispatch any events, including both "on" methods and events attached using addEventListener.
*/
this.dispatchEvent = function(event) {
if (typeof self["on" + event] === "function") {
self["on" + event]();
}
if (event in listeners) {
for (var i = 0, len = listeners[event].length; i < len; i++) {
listeners[event][i].call(self);
}
}
};
/**
* Changes readyState and calls onreadystatechange.
*
* @param int state New state
*/
var setState = function(state) {
if (state == self.LOADING || self.readyState !== state) {
self.readyState = state;
if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
self.dispatchEvent("readystatechange");
}
if (self.readyState === self.DONE && !errorFlag) {
self.dispatchEvent("load");
self.dispatchEvent("loadend");
}
}
};
};

View File

@ -1,541 +1,6 @@
const expect = require('expect'); const expect = require('expect');
const httpPost = (url, data, callback, err = console.error) => { const httpPost = require('./httpPost.js');
const request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.onload = () => callback(request.responseText);
request.onerror = () => err(request);
request.send(data);
};
test('httpPost is a Function', () => { test('httpPost is a Function', () => {
expect(httpPost).toBeInstanceOf(Function); expect(httpPost).toBeInstanceOf(Function);
}); });
const data = {
title: 'foo',
body: 'bar',
userId: 1
};
test('Sends a POST request', () => {
httpPost('https://jsonplaceholder.typicode.com/posts', JSON.stringify(data), response => {
expect(JSON.parse(response).id).toEqual(101);
});
});
var Url = require("url");
var spawn = require("child_process").spawn;
var fs = require("fs");
XMLHttpRequest = function() {
"use strict";
/**
* Private variables
*/
var self = this;
var http = require("http");
var https = require("https");
var request;
var response;
var settings = {};
var disableHeaderCheck = false;
var defaultHeaders = {
"User-Agent": "node-XMLHttpRequest",
"Accept": "*/*",
};
var headers = {};
var headersCase = {};
var forbiddenRequestHeaders = [
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"content-transfer-encoding",
"cookie",
"cookie2",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"via"
];
var forbiddenRequestMethods = [
"TRACE",
"TRACK",
"CONNECT"
];
var sendFlag = false;
var errorFlag = false;
var listeners = {};
/**
* Constants
*/
this.UNSENT = 0;
this.OPENED = 1;
this.HEADERS_RECEIVED = 2;
this.LOADING = 3;
this.DONE = 4;
/**
* Public vars
*/
this.readyState = this.UNSENT;
this.onreadystatechange = null;
this.responseText = "";
this.responseXML = "";
this.status = null;
this.statusText = null;
this.withCredentials = false;
/**
* Private methods
*/
/**
* Check if the specified header is allowed.
*
* @param string header Header to validate
* @return boolean False if not allowed, otherwise true
*/
var isAllowedHttpHeader = function(header) {
return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
};
/**
* Check if the specified method is allowed.
*
* @param string method Request method to validate
* @return boolean False if not allowed, otherwise true
*/
var isAllowedHttpMethod = function(method) {
return (method && forbiddenRequestMethods.indexOf(method) === -1);
};
/**
* Public methods
*/
/**
* Open the connection. Currently supports local server requests.
*
* @param string method Connection method (eg GET, POST)
* @param string url URL for the connection.
* @param boolean async Asynchronous connection. Default is true.
* @param string user Username for basic authentication (optional)
* @param string password Password for basic authentication (optional)
*/
this.open = function(method, url, async, user, password) {
this.abort();
errorFlag = false;
if (!isAllowedHttpMethod(method)) {
throw new Error("SecurityError: Request method not allowed");
}
settings = {
"method": method,
"url": url.toString(),
"async": (typeof async !== "boolean" ? true : async),
"user": user || null,
"password": password || null
};
setState(this.OPENED);
};
/**
* Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
* This does not conform to the W3C spec.
*
* @param boolean state Enable or disable header checking.
*/
this.setDisableHeaderCheck = function(state) {
disableHeaderCheck = state;
};
/**
* Sets a header for the request or appends the value if one is already set.
*
* @param string header Header name
* @param string value Header value
*/
this.setRequestHeader = function(header, value) {
if (this.readyState !== this.OPENED) {
throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
}
if (!isAllowedHttpHeader(header)) {
console.warn("Refused to set unsafe header \"" + header + "\"");
return;
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send flag is true");
}
header = headersCase[header.toLowerCase()] || header;
headersCase[header.toLowerCase()] = header;
headers[header] = headers[header] ? headers[header] + ', ' + value : value;
};
/**
* Gets a header from the server response.
*
* @param string header Name of header to get.
* @return string Text of the header or null if it doesn't exist.
*/
this.getResponseHeader = function(header) {
if (typeof header === "string"
&& this.readyState > this.OPENED
&& response
&& response.headers
&& response.headers[header.toLowerCase()]
&& !errorFlag
) {
return response.headers[header.toLowerCase()];
}
return null;
};
/**
* Gets all the response headers.
*
* @return string A string with all response headers separated by CR+LF
*/
this.getAllResponseHeaders = function() {
if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
return "";
}
var result = "";
for (var i in response.headers) {
if (i !== "set-cookie" && i !== "set-cookie2") {
result += i + ": " + response.headers[i] + "\r\n";
}
}
return result.substr(0, result.length - 2);
};
/**
* Gets a request header
*
* @param string name Name of header to get
* @return string Returns the request header or empty string if not set
*/
this.getRequestHeader = function(name) {
if (typeof name === "string" && headersCase[name.toLowerCase()]) {
return headers[headersCase[name.toLowerCase()]];
}
return "";
};
/**
* Sends the request to the server.
*
* @param string data Optional data to send as request body.
*/
this.send = function(data) {
if (this.readyState !== this.OPENED) {
throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");
}
if (sendFlag) {
throw new Error("INVALID_STATE_ERR: send has already been called");
}
var ssl = false, local = false;
var url = Url.parse(settings.url);
var host;
switch (url.protocol) {
case "https:":
ssl = true;
case "http:":
host = url.hostname;
break;
case "file:":
local = true;
break;
case undefined:
case null:
case "":
host = "localhost";
break;
default:
throw new Error("Protocol not supported.");
}
if (local) {
if (settings.method !== "GET") {
throw new Error("XMLHttpRequest: Only GET method is supported");
}
if (settings.async) {
fs.readFile(url.pathname, "utf8", function(error, data) {
if (error) {
self.handleError(error);
} else {
self.status = 200;
self.responseText = data;
setState(self.DONE);
}
} else {
try {
this.responseText = fs.readFileSync(url.pathname, "utf8");
this.status = 200;
setState(self.DONE);
} catch(e) {
this.handleError(e);
}
}
return;
}
var port = url.port || (ssl ? 443 : 80);
var uri = url.pathname + (url.search ? url.search : "");
for (var name in defaultHeaders) {
if (!headersCase[name.toLowerCase()]) {
headers[name] = defaultHeaders[name];
}
}
headers.Host = host;
if (!((ssl && port === 443) || port === 80)) {
headers.Host += ":" + url.port;
}
if (settings.user) {
if (typeof settings.password === "undefined") {
settings.password = "";
}
var authBuf = new Buffer(settings.user + ":" + settings.password);
headers.Authorization = "Basic " + authBuf.toString("base64");
}
if (settings.method === "GET" || settings.method === "HEAD") {
data = null;
} else if (data) {
headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
if (!headers["Content-Type"]) {
headers["Content-Type"] = "text/plain;charset=UTF-8";
}
} else if (settings.method === "POST") {
headers["Content-Length"] = 0;
}
var options = {
host: host,
port: port,
path: uri,
method: settings.method,
headers: headers,
agent: false,
withCredentials: self.withCredentials
};
errorFlag = false;
if (settings.async) {
var doRequest = ssl ? https.request : http.request;
sendFlag = true;
self.dispatchEvent("readystatechange");
var responseHandler = function responseHandler(resp) {
response = resp;
if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
settings.url = response.headers.location;
var url = Url.parse(settings.url);
host = url.hostname;
var newOptions = {
hostname: url.hostname,
port: url.port,
path: url.path,
method: response.statusCode === 303 ? "GET" : settings.method,
headers: headers,
withCredentials: self.withCredentials
};
request = doRequest(newOptions, responseHandler).on("error", errorHandler);
reques
return;
}
response.setEncoding("utf8");
setState(self.HEADERS_RECEIVED);
self.status = response.statusCode;
response.on("data", function(chunk) {
if (chunk) {
self.responseText += chunk;
}
if (sendFlag) {
setState(self.LOADING);
}
response.on("end", function() {
if (sendFlag) {
setState(self.DONE);
sendFlag = false;
}
response.on("error", function(error) {
self.handleError(error);
};
var errorHandler = function errorHandler(error) {
self.handleError(error);
};
request = doRequest(options, responseHandler).on("error", errorHandler);
if (data) {
request.write(data);
}
reques
self.dispatchEvent("loadstart");
} else {
var contentFile = ".node-xmlhttprequest-content-" + process.pid;
var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
fs.writeFileSync(syncFile, "", "utf8");
var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
+ "var doRequest = http" + (ssl ? "s" : "") + ".request;"
+ "var options = " + JSON.stringify(options) + ";"
+ "var responseText = '';"
+ "var req = doRequest(options, function(response) {"
+ "response.setEncoding('utf8');"
+ "response.on('data', function(chunk) {"
+ " responseText += chunk;"
+ ""
+ "response.on('end', function() {"
+ "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');"
+ "fs.unlinkSync('" + syncFile + "');"
+ ""
+ "response.on('error', function(error) {"
+ "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
+ "fs.unlinkSync('" + syncFile + "');"
+ ""
+ "}).on('error', function(error) {"
+ "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
+ "fs.unlinkSync('" + syncFile + "');"
+ ""
+ (data ? "req.write('" + JSON.stringify(data).slice(1,-1).replace(/'/g, "\\'") + "');":"")
+ "req.end();";
var syncProc = spawn(process.argv[0], ["-e", execString]);
while(fs.existsSync(syncFile)) {
}
var resp = JSON.parse(fs.readFileSync(contentFile, 'utf8'));
syncProc.stdin.end();
fs.unlinkSync(contentFile);
if (resp.err) {
self.handleError(resp.err);
} else {
response = resp.data;
self.status = resp.data.statusCode;
self.responseText = resp.data.text;
setState(self.DONE);
}
}
};
/**
* Called when an error is encountered to deal with it.
*/
this.handleError = function(error) {
this.status = 0;
this.statusText = error;
this.responseText = error.stack;
errorFlag = true;
setState(this.DONE);
this.dispatchEvent('error');
};
/**
* Aborts a request.
*/
this.abort = function() {
if (request) {
request.abort();
request = null;
}
headers = defaultHeaders;
this.status = 0;
this.responseText = "";
this.responseXML = "";
errorFlag = true;
if (this.readyState !== this.UNSENT
&& (this.readyState !== this.OPENED || sendFlag)
&& this.readyState !== this.DONE) {
sendFlag = false;
setState(this.DONE);
}
this.readyState = this.UNSENT;
this.dispatchEvent('abort');
};
/**
* Adds an event listener. Preferred method of binding to events.
*/
this.addEventListener = function(event, callback) {
if (!(event in listeners)) {
listeners[event] = [];
}
listeners[event].push(callback);
};
/**
* Remove an event callback that has already been bound.
* Only works on the matching funciton, cannot be a copy.
*/
this.removeEventListener = function(event, callback) {
if (event in listeners) {
listeners[event] = listeners[event].filter(function(ev) {
return ev !== callback;
}
};
/**
* Dispatch any events, including both "on" methods and events attached using addEventListener.
*/
this.dispatchEvent = function(event) {
if (typeof self["on" + event] === "function") {
self["on" + event]();
}
if (event in listeners) {
for (var i = 0, len = listeners[event].length; i < len; i++) {
listeners[event][i].call(self);
}
}
};
/**
* Changes readyState and calls onreadystatechange.
*
* @param int state New state
*/
var setState = function(state) {
if (state == self.LOADING || self.readyState !== state) {
self.readyState = state;
if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
self.dispatchEvent("readystatechange");
}
if (self.readyState === self.DONE && !errorFlag) {
self.dispatchEvent("load");
self.dispatchEvent("loadend");
}
}
};
};

View File

@ -14,5 +14,5 @@ test('The given number does not falls within the given range', () => {
expect(inRange(2, 3, 5)).toBeFalsy(); expect(inRange(2, 3, 5)).toBeFalsy();
}); });
test('The given number does not falls within the given range', () => { test('The given number does not falls within the given range', () => {
expect(inRange(3, 2)).toBeTruthy(); expect(inRange(3, 2)).toBeFalsy();
}); });

View File

@ -5,5 +5,5 @@ test('initial is a Function', () => {
expect(initial).toBeInstanceOf(Function); expect(initial).toBeInstanceOf(Function);
}); });
test('Returns all the elements of an array except the last one', () => { test('Returns all the elements of an array except the last one', () => {
expect(initial([1, 2, 3])).toEqual([1, 2])'' expect(initial([1, 2, 3])).toEqual([1, 2]);
}); });

View File

@ -4,9 +4,9 @@ const invertKeyValues = require('./invertKeyValues.js');
test('invertKeyValues is a Function', () => { test('invertKeyValues is a Function', () => {
expect(invertKeyValues).toBeInstanceOf(Function); expect(invertKeyValues).toBeInstanceOf(Function);
}); });
test('invertKeyValues({ a: 1, b: 2, c: 1 }) returns { 1: [ 'a', 'c' ], 2: [ 'b' ] }', () => { test('invertKeyValues({ a: 1, b: 2, c: 1 }) returns { 1: [ \'a\', \'c\' ], 2: [ \'b\' ] }', () => {
expect(invertKeyValues({ a: 1, b: 2, c: 1 })).toEqual({ 1: [ 'a', 'c' ], 2: [ 'b' ] }); expect(invertKeyValues({ a: 1, b: 2, c: 1 })).toEqual({ 1: [ 'a', 'c' ], 2: [ 'b' ] });
}); });
test('invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value) returns { group1: [ 'a', 'c' ], group2: [ 'b' ] }', () => { test('invertKeyValues({ a: 1, b: 2, c: 1 }, value => \'group\' + value) returns { group1: [ \'a\', \'c\' ], group2: [ \'b\' ] }', () => {
expect(invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value)).toEqual( { group1: [ 'a', 'c' ], group2: [ 'b' ] }); expect(invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value)).toEqual( { group1: [ 'a', 'c' ], group2: [ 'b' ] });
}); });

View File

@ -19,7 +19,7 @@ test('isPrimitive(true) is primitive', () => {
test('isPrimitive(50) is primitive', () => { test('isPrimitive(50) is primitive', () => {
expect(isPrimitive(50)).toBeTruthy(); expect(isPrimitive(50)).toBeTruthy();
}); });
test('isPrimitive('Hello') is primitive', () => { test('isPrimitive(\'Hello\') is primitive', () => {
expect(isPrimitive('Hello')).toBeTruthy(); expect(isPrimitive('Hello')).toBeTruthy();
}); });
test('isPrimitive(false) is primitive', () => { test('isPrimitive(false) is primitive', () => {
@ -35,7 +35,7 @@ test('isPrimitive({ a: 123 }) is not primitive', () => {
expect(isPrimitive({ a: 123 })).toBeFalsy(); expect(isPrimitive({ a: 123 })).toBeFalsy();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
isPrimitive({ a: 123 isPrimitive({ a: 123 });
let end = new Date().getTime(); let end = new Date().getTime();
test('isPrimitive({ a: 123 }) takes less than 2s to run', () => { test('isPrimitive({ a: 123 }) takes less than 2s to run', () => {
expect((end - start) < 2000).toBeTruthy(); expect((end - start) < 2000).toBeTruthy();

View File

@ -17,13 +17,13 @@ test('last(String) returns g', () => {
expect(last('String')).toBe('g'); expect(last('String')).toBe('g');
}); });
test('last(null) throws an Error', () => { test('last(null) throws an Error', () => {
expect(last(null)).toThrow(); expect(() => { last(null); }).toThrow();
}); });
test('last(undefined) throws an Error', () => { test('last(undefined) throws an Error', () => {
expect(last(undefined)).toThrow(); expect(() => { last(undefined); }).toThrow();
}); });
test('last() throws an Error', () => { test('last() throws an Error', () => {
expect(last()).toThrow(); expect(() => { last(); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]); last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]);

View File

@ -5,8 +5,8 @@ test('maxN is a Function', () => {
expect(maxN).toBeInstanceOf(Function); expect(maxN).toBeInstanceOf(Function);
}); });
test('Returns the n maximum elements from the provided array', () => { test('Returns the n maximum elements from the provided array', () => {
expect(maxN([1, 2, 3])).toEqual([3])l expect(maxN([1, 2, 3])).toEqual([3]);
}); });
test('Returns the n maximum elements from the provided array', () => { test('Returns the n maximum elements from the provided array', () => {
expect(maxN([1, 2, 3], 2)).toEqual([3, 2])l expect(maxN([1, 2, 3], 2)).toEqual([3, 2]);
}); });

View File

@ -5,11 +5,11 @@ test('pipeAsyncFunctions is a Function', () => {
expect(pipeAsyncFunctions).toBeInstanceOf(Function); expect(pipeAsyncFunctions).toBeInstanceOf(Function);
}); });
test('pipeAsyncFunctions result should be 15', () => { test('pipeAsyncFunctions result should be 15', () => {
expect(await pipeAsyncFunctions( expect(pipeAsyncFunctions(
(x) => x + 1, (x) => x + 1,
(x) => new Promise((resolve) => setTimeout(() => resolve(x + 2), 0)), (x) => new Promise((resolve) => setTimeout(() => resolve(x + 2), 0)),
(x) => x + 3, (x) => x + 3,
async (x) => await x + 4, async (x) => await x + 4,
) )
(5)).toBe(15); (5)).resolves.toBe(15);
}); });

View File

@ -11,19 +11,19 @@ test('quickSort([-1, 0, -2]) returns [-2, -1, 0]', () => {
expect(quickSort([-1, 0, -2])).toEqual([-2, -1, 0]); expect(quickSort([-1, 0, -2])).toEqual([-2, -1, 0]);
}); });
test('quickSort() throws an error', () => { test('quickSort() throws an error', () => {
expect(quickSort()).toThrow(); expect(() => { quickSort(); }).toThrow();
}); });
test('quickSort(123) throws an error', () => { test('quickSort(123) throws an error', () => {
expect(quickSort(123)).toThrow(); expect(() => { quickSort(123); }).toThrow();
}); });
test('quickSort({ 234: string}) throws an error', () => { test('quickSort({ 234: string}) throws an error', () => {
expect(quickSort({ 234: string})).toThrow(); expect(() => { quickSort({ 234: string}); }).toThrow();
}); });
test('quickSort(null) throws an error', () => { test('quickSort(null) throws an error', () => {
expect(quickSort(null)).toThrow(); expect(() => { quickSort(null); }).toThrow();
}); });
test('quickSort(undefined) throws an error', () => { test('quickSort(undefined) throws an error', () => {
expect(quickSort(undefined)).toThrow(); expect(() => { quickSort(undefined); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
quickSort([11, 1, 324, 23232, -1, 53, 2, 524, 32, 13, 156, 133, 62, 12, 4]); quickSort([11, 1, 324, 23232, -1, 53, 2, 524, 32, 13, 156, 133, 62, 12, 4]);

View File

@ -7,5 +7,5 @@ test('runPromisesInSeries is a Function', () => {
}); });
const delay = d => new Promise(r => setTimeout(r, d)); const delay = d => new Promise(r => setTimeout(r, d));
test('Runs promises in series', () => { test('Runs promises in series', () => {
runPromisesInSeries([() => delay(100), () => delay(200).then(() => expect(true).toBeTruthy())); runPromisesInSeries([() => delay(100), () => delay(200).then(() => expect(true).toBeTruthy())]);
}); });

View File

@ -6,7 +6,9 @@ test('shallowClone is a Function', () => {
}); });
const a = { foo: 'bar', obj: { a: 1, b: 2 } }; const a = { foo: 'bar', obj: { a: 1, b: 2 } };
const b = shallowClone(a); const b = shallowClone(a);
t.notEqual(a, b, 'Shallow cloning works'); test('Shallow cloning works', () => {
expect(a).not.toBe(b);
});
test('Does not clone deeply', () => { test('Does not clone deeply', () => {
expect(a.obj).toBe(b.obj); expect(a.obj).toBe(b.obj);
}); });

View File

@ -5,7 +5,7 @@ test('stringPermutations is a Function', () => {
expect(stringPermutations).toBeInstanceOf(Function); expect(stringPermutations).toBeInstanceOf(Function);
}); });
test('Generates all stringPermutations of a string', () => { test('Generates all stringPermutations of a string', () => {
expect(stringPermutations('abc'), ['abc','acb','bac','bca','cab').toEqual('cba']); expect(stringPermutations('abc')).toEqual(['abc','acb','bac','bca','cab','cba']);
}); });
test('Works for single-letter strings', () => { test('Works for single-letter strings', () => {
expect(stringPermutations('a')).toEqual(['a']); expect(stringPermutations('a')).toEqual(['a']);

View File

@ -5,7 +5,7 @@ test('tail is a Function', () => {
expect(tail).toBeInstanceOf(Function); expect(tail).toBeInstanceOf(Function);
}); });
test('Returns tail', () => { test('Returns tail', () => {
expect(tail([1, 2, 3]), [2).toEqual(3]); expect(tail([1, 2, 3])).toEqual([2, 3]);
}); });
test('Returns tail', () => { test('Returns tail', () => {
expect(tail([1])).toEqual([1]); expect(tail([1])).toEqual([1]);

View File

@ -5,8 +5,8 @@ test('take is a Function', () => {
expect(take).toBeInstanceOf(Function); expect(take).toBeInstanceOf(Function);
}); });
test('Returns an array with n elements removed from the beginning.', () => { test('Returns an array with n elements removed from the beginning.', () => {
expect(take([1, 2, 3], 5), [1, 2).toEqual(3]) expect(take([1, 2, 3], 5)).toEqual([1, 2, 3]);
}); });
test('Returns an array with n elements removed from the beginning.', () => { test('Returns an array with n elements removed from the beginning.', () => {
expect(take([1, 2, 3], 0)).toEqual([]) expect(take([1, 2, 3], 0)).toEqual([]);
}); });

File diff suppressed because it is too large Load Diff

View File

@ -4,29 +4,29 @@ const toCamelCase = require('./toCamelCase.js');
test('toCamelCase is a Function', () => { test('toCamelCase is a Function', () => {
expect(toCamelCase).toBeInstanceOf(Function); expect(toCamelCase).toBeInstanceOf(Function);
}); });
test('toCamelCase('some_database_field_name') returns someDatabaseFieldName', () => { test('toCamelCase(\'some_database_field_name\') returns someDatabaseFieldName', () => {
expect(toCamelCase('some_database_field_name')).toBe('someDatabaseFieldName'); expect(toCamelCase('some_database_field_name')).toBe('someDatabaseFieldName');
}); });
test('toCamelCase('Some label that needs to be camelized') returns someLabelThatNeedsToBeCamelized', () => { test('toCamelCase(\'Some label that needs to be camelized\') returns someLabelThatNeedsToBeCamelized', () => {
expect(toCamelCase('Some label that needs to be camelized')).toBe('someLabelThatNeedsToBeCamelized'); expect(toCamelCase('Some label that needs to be camelized')).toBe('someLabelThatNeedsToBeCamelized');
}); });
test('toCamelCase('some-javascript-property') return someJavascriptProperty', () => { test('toCamelCase(\'some-javascript-property\') return someJavascriptProperty', () => {
expect(toCamelCase('some-javascript-property')).toBe('someJavascriptProperty'); expect(toCamelCase('some-javascript-property')).toBe('someJavascriptProperty');
}); });
test('toCamelCase('some-mixed_string with spaces_underscores-and-hyphens') returns someMixedStringWithSpacesUnderscoresAndHyphens', () => { test('toCamelCase(\'some-mixed_string with spaces_underscores-and-hyphens\') returns someMixedStringWithSpacesUnderscoresAndHyphens', () => {
expect(toCamelCase('some-mixed_string with spaces_underscores-and-hyphens')).toBe('someMixedStringWithSpacesUnderscoresAndHyphens'); expect(toCamelCase('some-mixed_string with spaces_underscores-and-hyphens')).toBe('someMixedStringWithSpacesUnderscoresAndHyphens');
}); });
test('toCamelCase() throws a error', () => { test('toCamelCase() throws a error', () => {
expect(toCamelCase()).toThrow(); expect(() => {toCamelCase(); }).toThrow();
}); });
test('toCamelCase([]) throws a error', () => { test('toCamelCase([]) throws a error', () => {
expect(toCamelCase([])).toThrow(); expect(() => {toCamelCase([]); }).toThrow();
}); });
test('toCamelCase({}) throws a error', () => { test('toCamelCase({}) throws a error', () => {
expect(toCamelCase({})).toThrow(); expect(() => {toCamelCase({}); }).toThrow();
}); });
test('toCamelCase(123) throws a error', () => { test('toCamelCase(123) throws a error', () => {
expect(toCamelCase(123)).toThrow(); expect(() => {toCamelCase(123); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');

View File

@ -5,11 +5,11 @@ test('toCurrency is a Function', () => {
expect(toCurrency).toBeInstanceOf(Function); expect(toCurrency).toBeInstanceOf(Function);
}); });
test('currency: Euro | currencyLangFormat: Local', () => { test('currency: Euro | currencyLangFormat: Local', () => {
expect(toCurrency(123456.789, 'EUR'), '€ 123,456.79').stringMatching(/€\s*123,456.79/g); expect(toCurrency(123456.789, 'EUR')).toEqual(expect.stringMatching(/€\s*123,456.79/g));
}); });
test(' currency: US Dollar | currencyLangFormat: English (United States)', () => { test(' currency: US Dollar | currencyLangFormat: English (United States)', () => {
expect(toCurrency(123456.789, 'USD', 'en-us')).stringMatching(/\$\s*123,456.79/g); expect(toCurrency(123456.789, 'USD', 'en-us')).toEqual(expect.stringMatching(/\$\s*123,456.79/g));
}); });
test('currency: Japanese Yen | currencyLangFormat: Local', () => { test('currency: Japanese Yen | currencyLangFormat: Local', () => {
expect(toCurrency(322342436423.2435, 'JPY'), 'JP¥ 322,342,436,423').stringMatching(/J*P*¥\s*322,342,436,423/g); expect(toCurrency(322342436423.2435, 'JPY')).toEqual(expect.stringMatching(/J*P*¥\s*322,342,436,423/g));
}); });

View File

@ -20,13 +20,13 @@ test('toKebabCase() returns undefined', () => {
expect(toKebabCase()).toBe(undefined) expect(toKebabCase()).toBe(undefined)
}); });
test('toKebabCase([]) throws an erro', () => { test('toKebabCase([]) throws an erro', () => {
expect(toKebabCase([])).toThrow(); expect(() => { toKebabCase([]); }).toThrow();
}); });
test('toKebabCase({}) throws an erro', () => { test('toKebabCase({}) throws an erro', () => {
expect(toKebabCase({})).toThrow(); expect(() => { toKebabCase({}); }).toThrow();
}); });
test('toKebabCase(123) throws an erro', () => { test('toKebabCase(123) throws an erro', () => {
expect(toKebabCase(123)).toThrow(); expect(() => { toKebabCase(123); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML');

View File

@ -10,7 +10,7 @@ test('Number(toSafeInteger(3.2)) is a number', () => {
test('Converts a value to a safe integer', () => { test('Converts a value to a safe integer', () => {
expect(toSafeInteger(3.2)).toBe(3); expect(toSafeInteger(3.2)).toBe(3);
}); });
test('toSafeInteger('4.2') returns 4', () => { test('toSafeInteger(\'4.2\') returns 4', () => {
expect(toSafeInteger('4.2')).toBe(4); expect(toSafeInteger('4.2')).toBe(4);
}); });
test('toSafeInteger(4.6) returns 5', () => { test('toSafeInteger(4.6) returns 5', () => {
@ -22,7 +22,7 @@ test('toSafeInteger([]) returns 0', () => {
test('isNaN(toSafeInteger([1.5, 3124])) is true', () => { test('isNaN(toSafeInteger([1.5, 3124])) is true', () => {
expect(isNaN(toSafeInteger([1.5, 3124]))).toBeTruthy(); expect(isNaN(toSafeInteger([1.5, 3124]))).toBeTruthy();
}); });
test('isNaN(toSafeInteger('string')) is true', () => { test('isNaN(toSafeInteger(\'string\')) is true', () => {
expect(isNaN(toSafeInteger('string'))).toBeTruthy(); expect(isNaN(toSafeInteger('string'))).toBeTruthy();
}); });
test('isNaN(toSafeInteger({})) is true', () => { test('isNaN(toSafeInteger({})) is true', () => {

View File

@ -4,7 +4,7 @@ const toSnakeCase = require('./toSnakeCase.js');
test('toSnakeCase is a Function', () => { test('toSnakeCase is a Function', () => {
expect(toSnakeCase).toBeInstanceOf(Function); expect(toSnakeCase).toBeInstanceOf(Function);
}); });
test('toSnakeCase('\camelCase\') returns camel_case', () => { test('toSnakeCase(\'camelCase\') returns camel_case', () => {
expect(toSnakeCase('camelCase')).toBe('camel_case'); expect(toSnakeCase('camelCase')).toBe('camel_case');
}); });
test('toSnakeCase(\'some text\') returns some_text', () => { test('toSnakeCase(\'some text\') returns some_text', () => {
@ -20,13 +20,13 @@ test('toSnakeCase() returns undefined', () => {
expect(toSnakeCase()).toBe(undefined); expect(toSnakeCase()).toBe(undefined);
}); });
test('toSnakeCase([]) throws an error', () => { test('toSnakeCase([]) throws an error', () => {
expect(toSnakeCase([])).toThrow(); expect(() => {toSnakeCase([]);}).toThrow();
}); });
test('toSnakeCase({}) throws an error', () => { test('toSnakeCase({}) throws an error', () => {
expect(toSnakeCase({})).toThrow(); expect(() => {toSnakeCase({});}).toThrow();
}); });
test('toSnakeCase(123) throws an error', () => { test('toSnakeCase(123) throws an error', () => {
expect(toSnakeCase(123)).toThrow(); expect(() => {toSnakeCase(123);}).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML');

View File

@ -10,5 +10,5 @@ test('Transforms an object', () => {
(r, v, k) => { (r, v, k) => {
(r[v] || (r[v] = [])).push(k); (r[v] || (r[v] = [])).push(k);
return r; return r;
},{}).toEqual({ '1': ['a', 'c'], '2': ['b'] }); },{})).toEqual({ '1': ['a', 'c'], '2': ['b'] });
}); });

View File

@ -7,7 +7,7 @@ test('union is a Function', () => {
test('union([1, 2, 3], [4, 3, 2]) returns [1, 2, 3, 4]', () => { test('union([1, 2, 3], [4, 3, 2]) returns [1, 2, 3, 4]', () => {
expect(union([1, 2, 3], [4, 3, 2])).toEqual([1, 2, 3, 4]); expect(union([1, 2, 3], [4, 3, 2])).toEqual([1, 2, 3, 4]);
}); });
test('union('str', 'asd') returns [ 's', 't', 'r', 'a', 'd' ]', () => { test('union(\'str\', \'asd\') returns [ \'s\', \'t\', \'r\', \'a\', \'d\' ]', () => {
expect(union('str', 'asd')).toEqual([ 's', 't', 'r', 'a', 'd' ]); expect(union('str', 'asd')).toEqual([ 's', 't', 'r', 'a', 'd' ]);
}); });
test('union([[], {}], [1, 2, 3]) returns [[], {}, 1, 2, 3]', () => { test('union([[], {}], [1, 2, 3]) returns [[], {}, 1, 2, 3]', () => {
@ -17,22 +17,22 @@ test('union([], []) returns []', () => {
expect(union([], [])).toEqual([]); expect(union([], [])).toEqual([]);
}); });
test('union() throws an error', () => { test('union() throws an error', () => {
expect(union()).toThrow(); expect(() => {union(); }).toThrow();
}); });
test('union(true, \'str\') throws an error', () => { test('union(true, \'str\') throws an error', () => {
expect(union(true, 'str')).toThrow(); expect(() => {union(true, 'str'); }).toThrow();
}); });
test('union(\'false\', true) throws an error', () => { test('union(\'false\', true) throws an error', () => {
expect(union('false', true)).toThrow(); expect(() => {union('false', true); }).toThrow();
}); });
test('union((123, {}) throws an error', () => { test('union((123, {}) throws an error', () => {
expect(union((123, {})).toThrow(); expect(() => {union(123, {}); }).toThrow();
}); });
test('union([], {}) throws an error', () => { test('union([], {}) throws an error', () => {
expect(union([], {})).toThrow(); expect(() => {union([], {}); }).toThrow();
}); });
test('union(undefined, null) throws an error', () => { test('union(undefined, null) throws an error', () => {
expect(union(undefined, null)).toThrow(); expect(() => {union(undefined, null); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
union([1, 2, 3], [4, 3, 2]); union([1, 2, 3], [4, 3, 2]);

View File

@ -11,7 +11,7 @@ test('uniqueElements([1, 2, 2, 3, 4, 4, 5]) returns [1,2,3,4,5]', () => {
test('uniqueElements([1, 23, 53]) returns [1, 23, 53]', () => { test('uniqueElements([1, 23, 53]) returns [1, 23, 53]', () => {
expect(uniqueElements([1, 23, 53])).toEqual([1, 23, 53]); expect(uniqueElements([1, 23, 53])).toEqual([1, 23, 53]);
}); });
test('uniqueElements([true, 0, 1, false, false, undefined, null, '']) returns [true, 0, 1, false, false, undefined, null, '']', () => { test('uniqueElements([true, 0, 1, false, false, undefined, null, \'\']) returns [true, 0, 1, false, false, undefined, null, \'\']', () => {
expect(uniqueElements([true, 0, 1, false, false, undefined, null, ''])).toEqual([true, 0, 1, false, undefined, null, '']); expect(uniqueElements([true, 0, 1, false, false, undefined, null, ''])).toEqual([true, 0, 1, false, undefined, null, '']);
}); });
test('uniqueElements() returns []', () => { test('uniqueElements() returns []', () => {
@ -23,20 +23,20 @@ test('uniqueElements(null) returns []', () => {
test('uniqueElements(undefined) returns []', () => { test('uniqueElements(undefined) returns []', () => {
expect(uniqueElements(undefined)).toEqual([]); expect(uniqueElements(undefined)).toEqual([]);
}); });
test('uniqueElements(\'strt\') returns ['s', 't', 'r']', () => { test('uniqueElements(\'strt\') returns [\'s\', \'t\', \'r\']', () => {
expect(uniqueElements('strt')).toEqual(['s', 't', 'r']); expect(uniqueElements('strt')).toEqual(['s', 't', 'r']);
}); });
test('uniqueElements(1, 1, 2543, 534, 5) throws an error', () => { test('uniqueElements(1, 1, 2543, 534, 5) throws an error', () => {
expect(uniqueElements(1, 1, 2543, 534, 5)).toThrow(); expect(() => {uniqueElements(1, 1, 2543, 534, 5); }).toThrow();
}); });
test('uniqueElements({}) throws an error', () => { test('uniqueElements({}) throws an error', () => {
expect(uniqueElements({})).toThrow(); expect(() => {uniqueElements({}); }).toThrow();
}); });
test('uniqueElements(true) throws an error', () => { test('uniqueElements(true) throws an error', () => {
expect(uniqueElements(true)).toThrow(); expect(() => {uniqueElements(true); }).toThrow();
}); });
test('uniqueElements(false) throws an error', () => { test('uniqueElements(false) throws an error', () => {
expect(uniqueElements(false)).toThrow(); expect(() => {uniqueElements(false); }).toThrow();
}); });
let start = new Date().getTime(); let start = new Date().getTime();
uniqueElements([true, 0, 1, false, false, undefined, null, '']); uniqueElements([true, 0, 1, false, false, undefined, null, '']);

View File

@ -5,8 +5,8 @@ test('unzip is a Function', () => {
expect(unzip).toBeInstanceOf(Function); expect(unzip).toBeInstanceOf(Function);
}); });
test('unzip([[\'a\', 1, true], [\'b\', 2, false]]) equals [[\'a\',\'b\'], [1, 2], [true, false]]', () => { test('unzip([[\'a\', 1, true], [\'b\', 2, false]]) equals [[\'a\',\'b\'], [1, 2], [true, false]]', () => {
expect(unzip([['a', 1, true], ['b', 2, false]])).toBe([['a', 'b'], [1, 2], [true, false]]); expect(unzip([['a', 1, true], ['b', 2, false]])).toEqual([['a', 'b'], [1, 2], [true, false]]);
}); });
test('unzip([[\'a\', 1, true], [\'b\', 2]]) equals [[\'a\',\'b\'], [1, 2], [true]]', () => { test('unzip([[\'a\', 1, true], [\'b\', 2]]) equals [[\'a\',\'b\'], [1, 2], [true]]', () => {
expect(unzip([['a', 1, true], ['b', 2]])).toBe([['a', 'b'], [1, 2], [true]]); expect(unzip([['a', 1, true], ['b', 2]])).toEqual([['a', 'b'], [1, 2], [true]]);
}); });

View File

@ -5,5 +5,5 @@ test('unzipWith is a Function', () => {
expect(unzipWith).toBeInstanceOf(Function); expect(unzipWith).toBeInstanceOf(Function);
}); });
test('unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)) equals [3, 30, 300]', () => { test('unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)) equals [3, 30, 300]', () => {
expect(unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0))).toBe([3, 30, 300]); expect(unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0))).toEqual([3, 30, 300]);
}); });

View File

@ -10,24 +10,24 @@ test('without([2, 1, 2, 3], 1, 2) returns [3]', () => {
test('without([]) returns []', () => { test('without([]) returns []', () => {
expect(without([])).toEqual([]); expect(without([])).toEqual([]);
}); });
test('without([3, 1, true, '3', true], '3', true) returns [3, 1]', () => { test('without([3, 1, true, \'3\', true], \'3\', true) returns [3, 1]', () => {
expect(without([3, 1, true, '3', true], '3', true)).toEqual([3, 1]); expect(without([3, 1, true, '3', true], '3', true)).toEqual([3, 1]);
}); });
test('without('string'.split(''), 's', 't', 'g') returns [\'r\', \'i\', \'n\']', () => { test('without(\'string\'.split(\'\'), \'s\', \'t\', \'g\') returns [\'r\', \'i\', \'n\']', () => {
expect(without('string'.split(''), 's', 't', 'g')).toEqual(['r', 'i', 'n']); expect(without('string'.split(''), 's', 't', 'g')).toEqual(['r', 'i', 'n']);
}); });
test('without() throws an error', () => { test('without() throws an error', () => {
expect(without()).toThrow(); expect(() => { without(); }).toThrow();
}); });
test('without(null) throws an error', () => { test('without(null) throws an error', () => {
expect(without(null)).toThrow(); expect(() => { without(null); }).toThrow();
}); });
test('without(undefined) throws an error', () => { test('without(undefined) throws an error', () => {
expect(without(undefined)).toThrow(); expect(() => { without(undefined); }).toThrow();
}); });
test('without(123) throws an error', () => { test('without(123) throws an error', () => {
expect(without(123)).toThrow(); expect(() => { without(123); }).toThrow();
}); });
test('without({}) throws an error', () => { test('without({}) throws an error', () => {
expect(without({})).toThrow(); expect(() => { without({}); }).toThrow();
}); });

View File

@ -4,30 +4,30 @@ const words = require('./words.js');
test('words is a Function', () => { test('words is a Function', () => {
expect(words).toBeInstanceOf(Function); expect(words).toBeInstanceOf(Function);
}); });
test('words('I love javaScript!!') returns [I, love, javaScript]', () => { test('words(\'I love javaScript!!\') returns [I, love, javaScript]', () => {
expect(words('I love javaScript!!')).toEqual(["I", "love", "javaScript"]); expect(words('I love javaScript!!')).toEqual(["I", "love", "javaScript"]);
}); });
test('words('python, javaScript & coffee') returns [python, javaScript, coffee]', () => { test('words(\'python, javaScript & coffee\') returns [python, javaScript, coffee]', () => {
expect(words('python, javaScript & coffee')).toEqual(["python", "javaScript", "coffee"]); expect(words('python, javaScript & coffee')).toEqual(["python", "javaScript", "coffee"]);
}); });
test('words(I love javaScript!!) returns an array', () => { test('words(I love javaScript!!) returns an array', () => {
expect(Array.isArray(words('I love javaScript!!'))).toBeTruthy(); expect(Array.isArray(words('I love javaScript!!'))).toBeTruthy();
}); });
test('words() throws an error', () => { test('words() throws an error', () => {
expect(words()).toThrow(); expect(() => { words(); }).toThrow();
}); });
test('words(null) throws an error', () => { test('words(null) throws an error', () => {
expect(words(null)).toThrow(); expect(() => { words(null); }).toThrow();
}); });
test('words(undefined) throws an error', () => { test('words(undefined) throws an error', () => {
expect(words(undefined)).toThrow(); expect(() => { words(undefined); }).toThrow();
}); });
test('words({}) throws an error', () => { test('words({}) throws an error', () => {
expect(words({})).toThrow(); expect(() => { words({}); }).toThrow();
}); });
test('words([]) throws an error', () => { test('words([]) throws an error', () => {
expect(words([])).toThrow(); expect(() => { words([]); }).toThrow();
}); });
test('words(1234) throws an error', () => { test('words(1234) throws an error', () => {
expect(words(1234)).toThrow(); expect(() => { words(1234); }).toThrow();
}); });

View File

@ -24,8 +24,8 @@ test('zip([a], [1, 2], [true, false]) returns an Array', () => {
expect(Array.isArray(zip(['a'], [1, 2], [true, false]))).toBeTruthy(); expect(Array.isArray(zip(['a'], [1, 2], [true, false]))).toBeTruthy();
}); });
test('zip(null) throws an error', () => { test('zip(null) throws an error', () => {
expect(zip(null)).toThrow(); expect(() => {zip(null);}).toThrow();
}); });
test('zip(undefined) throws an error', () => { test('zip(undefined) throws an error', () => {
expect(zip(undefined)).toThrow(); expect(() => {zip(undefined);}).toThrow();
}); });

View File

@ -17,17 +17,17 @@ test('zipObject([a], string) returns { a: s }', () => {
expect(zipObject(['a'], 'string')).toEqual({ a: 's' }); expect(zipObject(['a'], 'string')).toEqual({ a: 's' });
}); });
test('zipObject() throws an error', () => { test('zipObject() throws an error', () => {
expect(zipObject()).toThrow(); expect(() => {zipObject();}).toThrow();
}); });
test('zipObject(([\'string\'], null) throws an error', () => { test('zipObject(([\'string\'], null) throws an error', () => {
expect(zipObject((['string'], null)).toThrow(); expect(() => {zipObject(['string'], null);}).toThrow();
}); });
test('zipObject(null, [1]) throws an error', () => { test('zipObject(null, [1]) throws an error', () => {
expect(zipObject(null, [1])).toThrow(); expect(() => {zipObject(null, [1]);}).toThrow();
}); });
test('zipObject(\'string\') throws an error', () => { test('zipObject(\'string\') throws an error', () => {
expect(zipObject('string')).toThrow(); expect(() => {zipObject('string');}).toThrow();
}); });
test('zipObject(\'test\', \'string\') throws an error', () => { test('zipObject(\'test\', \'string\') throws an error', () => {
expect(zipObject('test', 'string')).toThrow(); expect(() => {zipObject('test', 'string');}).toThrow();
}); });