Final fixes, all tests running
This commit is contained in:
70
package-lock.json
generated
70
package-lock.json
generated
@ -5137,6 +5137,48 @@
|
||||
"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": {
|
||||
"version": "23.1.0",
|
||||
"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": {
|
||||
"version": "1.1.2",
|
||||
"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": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
|
||||
|
||||
17
package.json
17
package.json
@ -5,6 +5,7 @@
|
||||
"fs-extra": "^6.0.0",
|
||||
"html-minifier": "^3.5.15",
|
||||
"jest": "^23.1.0",
|
||||
"jest-tap-reporter": "^1.9.0",
|
||||
"jsdom": "^11.10.0",
|
||||
"markdown-it": "^8.4.1",
|
||||
"mini.css": "^2.3.7",
|
||||
@ -16,8 +17,6 @@
|
||||
"rollup-plugin-babel": "^3.0.4",
|
||||
"rollup-plugin-babel-minify": "^4.0.0",
|
||||
"semistandard": "^12.0.1",
|
||||
"tap-spec": "^4.1.1",
|
||||
"tape": "^4.9.0"
|
||||
},
|
||||
"name": "30-seconds-of-code",
|
||||
"description": "A collection of useful JavaScript snippets.",
|
||||
@ -33,8 +32,7 @@
|
||||
"extractor": "node ./scripts/extract.js",
|
||||
"packager": "node ./scripts/module.js",
|
||||
"localizer": "node ./scripts/localize.js",
|
||||
"testold": "tape test/**/*.test.js | tap-spec",
|
||||
"test": "jest test/**/*.test.js"
|
||||
"test": "jest --verbose"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -51,5 +49,14 @@
|
||||
"url": "https://github.com/Chalarangelo/30-seconds-of-code/issues"
|
||||
},
|
||||
"homepage": "https://github.com/Chalarangelo/30-seconds-of-code#readme",
|
||||
"dependencies": {}
|
||||
"dependencies": {},
|
||||
"jest": {
|
||||
"reporters": [
|
||||
["jest-tap-reporter", {
|
||||
"logLevel": "INFO",
|
||||
"showInternalStackTraces": false,
|
||||
"filePath": "test/testlog"
|
||||
}]
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@ -84,7 +84,7 @@ snippetFiles
|
||||
});
|
||||
try {
|
||||
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) {
|
||||
fs.appendFileSync(path.join(TEST_PATH,'testlog'));
|
||||
|
||||
@ -5,5 +5,5 @@ test('call is a Function', () => {
|
||||
expect(call).toBeInstanceOf(Function);
|
||||
});
|
||||
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]);
|
||||
});
|
||||
|
||||
@ -8,7 +8,7 @@ test('Capitalizes the first letter of a string', () => {
|
||||
expect(capitalize('fooBar')).toBe('FooBar');
|
||||
});
|
||||
test('Capitalizes the first letter of a string', () => {
|
||||
expect(capitalize('fooBar', true)).toBe('FooBar');
|
||||
expect(capitalize('fooBar', true)).toBe('Foobar');
|
||||
});
|
||||
test('Works with characters', () => {
|
||||
expect(capitalize('#!#', true)).toBe('#!#');
|
||||
|
||||
@ -5,7 +5,7 @@ test('capitalizeEveryWord is a Function', () => {
|
||||
expect(capitalizeEveryWord).toBeInstanceOf(Function);
|
||||
});
|
||||
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', () => {
|
||||
expect(capitalizeEveryWord('$# @!')).toBe('$# @!');
|
||||
|
||||
@ -5,7 +5,7 @@ test('chunk is a Function', () => {
|
||||
expect(chunk).toBeInstanceOf(Function);
|
||||
});
|
||||
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 []', () => {
|
||||
expect(chunk([])).toEqual([])
|
||||
@ -20,13 +20,13 @@ test('chunk(string, 2) returns [ st, ri, ng ]', () => {
|
||||
expect(chunk('string', 2)).toEqual( [ 'st', 'ri', 'ng' ])
|
||||
});
|
||||
test('chunk() throws an error', () => {
|
||||
expect(chunk()).toThrow();
|
||||
expect(() => {chunk();}).toThrow();
|
||||
});
|
||||
test('chunk(undefined) throws an error', () => {
|
||||
expect(chunk(undefined)).toThrow();
|
||||
expect(() => {chunk(undefined);}).toThrow();
|
||||
});
|
||||
test('chunk(null) throws an error', () => {
|
||||
expect(chunk(null)).toThrow();
|
||||
expect(() => {chunk(null);}).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
chunk('This is a string', 2);
|
||||
|
||||
@ -6,5 +6,5 @@ test('cloneRegExp is a Function', () => {
|
||||
});
|
||||
const rgTest = /./g;
|
||||
test('Clones regular expressions properly', () => {
|
||||
expect(cloneRegExp(rgTest).not.toEqual(rgTest);
|
||||
expect(cloneRegExp(rgTest)).not.toBe(rgTest);
|
||||
});
|
||||
|
||||
@ -9,14 +9,14 @@ const b = deepClone(a);
|
||||
const c = [{foo: "bar"}];
|
||||
const d = deepClone(c);
|
||||
test('Shallow cloning works', () => {
|
||||
expect(a).not.toEqual(b);
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
test('Deep cloning works', () => {
|
||||
expect(a.obj).not.toEqual(b.obj);
|
||||
expect(a.obj).not.toBe(b.obj);
|
||||
});
|
||||
test('Array shallow cloning works', () => {
|
||||
expect(c).not.toEqual(d);
|
||||
expect(c).not.toBe(d);
|
||||
});
|
||||
test('Array deep cloning works', () => {
|
||||
expect(c[0]).not.toEqual(d[0]);
|
||||
expect(c[0]).not.toBe(d[0]);
|
||||
});
|
||||
|
||||
@ -5,5 +5,5 @@ test('defaults is a Function', () => {
|
||||
expect(defaults).toBeInstanceOf(Function);
|
||||
});
|
||||
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 });
|
||||
});
|
||||
|
||||
@ -8,7 +8,7 @@ test('Standard 1v1s', () => {
|
||||
expect(elo([1200, 1200])).toEqual([1216,1184]);
|
||||
});
|
||||
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', () => {
|
||||
expect(elo([1200, 1200, 1200, 1200]).map(Math.round)).toEqual([1246, 1215, 1185, 1154]);
|
||||
|
||||
@ -4,7 +4,7 @@ const equals = require('./equals.js');
|
||||
test('equals is a 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();
|
||||
});
|
||||
test('[1,2,3] is equal to [1,2,3]', () => {
|
||||
|
||||
@ -11,5 +11,5 @@ test('Returns the appropriate key', () => {
|
||||
fred: { age: 40, active: false },
|
||||
pebbles: { age: 1, active: true }
|
||||
},
|
||||
o => o['active']).toBe('barney');
|
||||
o => o['active'])).toBe('barney');
|
||||
});
|
||||
|
||||
@ -11,5 +11,5 @@ test('eturns the appropriate key', () => {
|
||||
fred: { age: 40, active: false },
|
||||
pebbles: { age: 1, active: true }
|
||||
},
|
||||
o => o['active']).toBe('pebbles');
|
||||
o => o['active'])).toBe('pebbles');
|
||||
});
|
||||
|
||||
@ -1,23 +1,18 @@
|
||||
const expect = require('expect');
|
||||
let output = '';
|
||||
const console = {};
|
||||
console.debug = (x) => output = x;
|
||||
const functionName = fn => (console.debug(fn.name), fn);
|
||||
const functionName = fn => fn.name;
|
||||
|
||||
test('functionName is a Function', () => {
|
||||
expect(functionName).toBeInstanceOf(Function);
|
||||
});
|
||||
functionName(Math.max);
|
||||
test('Works for native functions', () => {
|
||||
expect(output).toBe('max');
|
||||
expect(functionName(Math.max)).toBe('max');
|
||||
});
|
||||
function fun(x) {return x;}
|
||||
functionName(fun);
|
||||
test('Works for functions', () => {
|
||||
expect(output).toBe('fun');
|
||||
expect(functionName(fun)).toBe('fun');
|
||||
});
|
||||
const fn = x => x;
|
||||
functionName(fn);
|
||||
test('Works for arrow functions', () => {
|
||||
expect(output).toBe('fn');
|
||||
expect(functionName(fn)).toBe('fn');
|
||||
});
|
||||
|
||||
@ -10,7 +10,7 @@ function Foo() {
|
||||
}
|
||||
Foo.prototype.c = () => 3;
|
||||
test('Returns own methods', () => {
|
||||
expect(functions(new Foo()).toEqual( ['a', 'b']);
|
||||
expect(functions(new Foo())).toEqual( ['a', 'b']);
|
||||
});
|
||||
test('Returns own and inherited methods', () => {
|
||||
expect(functions(new Foo(), true)).toEqual(['a', 'b', 'c']);
|
||||
|
||||
@ -5,5 +5,5 @@ test('getURLParameters is a Function', () => {
|
||||
expect(getURLParameters).toBeInstanceOf(Function);
|
||||
});
|
||||
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'});
|
||||
});
|
||||
|
||||
@ -17,13 +17,13 @@ test('head(String) returns S', () => {
|
||||
expect(head('String')).toBe('S');
|
||||
});
|
||||
test('head(null) throws an Error', () => {
|
||||
expect(head(null)).toThrow();
|
||||
expect(() => { head(null); }).toThrow();
|
||||
});
|
||||
test('head(undefined) throws an Error', () => {
|
||||
expect(head(undefined)).toThrow();
|
||||
expect(() => { head(undefined); }).toThrow();
|
||||
});
|
||||
test('head() throws an Error', () => {
|
||||
expect(head()).toThrow();
|
||||
expect(() => { head(); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]);
|
||||
|
||||
@ -1,541 +1,6 @@
|
||||
const expect = require('expect');
|
||||
const httpGet = (url, callback, err = console.error) => {
|
||||
const request = new XMLHttpRequest();
|
||||
request.open('GET', url, true);
|
||||
request.onload = () => callback(request.responseText);
|
||||
request.onerror = () => err(request);
|
||||
request.send();
|
||||
};
|
||||
const httpGet = require('./httpGet.js');
|
||||
|
||||
test('httpGet is a 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");
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@ -1,541 +1,6 @@
|
||||
const expect = require('expect');
|
||||
const httpPost = (url, data, callback, err = console.error) => {
|
||||
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);
|
||||
};
|
||||
const httpPost = require('./httpPost.js');
|
||||
|
||||
test('httpPost is a 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");
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
@ -14,5 +14,5 @@ test('The given number does not falls within the given range', () => {
|
||||
expect(inRange(2, 3, 5)).toBeFalsy();
|
||||
});
|
||||
test('The given number does not falls within the given range', () => {
|
||||
expect(inRange(3, 2)).toBeTruthy();
|
||||
expect(inRange(3, 2)).toBeFalsy();
|
||||
});
|
||||
|
||||
@ -5,5 +5,5 @@ test('initial is a Function', () => {
|
||||
expect(initial).toBeInstanceOf(Function);
|
||||
});
|
||||
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]);
|
||||
});
|
||||
|
||||
@ -4,9 +4,9 @@ const invertKeyValues = require('./invertKeyValues.js');
|
||||
test('invertKeyValues is a 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' ] });
|
||||
});
|
||||
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' ] });
|
||||
});
|
||||
|
||||
@ -19,7 +19,7 @@ test('isPrimitive(true) is primitive', () => {
|
||||
test('isPrimitive(50) is primitive', () => {
|
||||
expect(isPrimitive(50)).toBeTruthy();
|
||||
});
|
||||
test('isPrimitive('Hello') is primitive', () => {
|
||||
test('isPrimitive(\'Hello\') is primitive', () => {
|
||||
expect(isPrimitive('Hello')).toBeTruthy();
|
||||
});
|
||||
test('isPrimitive(false) is primitive', () => {
|
||||
@ -35,7 +35,7 @@ test('isPrimitive({ a: 123 }) is not primitive', () => {
|
||||
expect(isPrimitive({ a: 123 })).toBeFalsy();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
isPrimitive({ a: 123
|
||||
isPrimitive({ a: 123 });
|
||||
let end = new Date().getTime();
|
||||
test('isPrimitive({ a: 123 }) takes less than 2s to run', () => {
|
||||
expect((end - start) < 2000).toBeTruthy();
|
||||
|
||||
@ -17,13 +17,13 @@ test('last(String) returns g', () => {
|
||||
expect(last('String')).toBe('g');
|
||||
});
|
||||
test('last(null) throws an Error', () => {
|
||||
expect(last(null)).toThrow();
|
||||
expect(() => { last(null); }).toThrow();
|
||||
});
|
||||
test('last(undefined) throws an Error', () => {
|
||||
expect(last(undefined)).toThrow();
|
||||
expect(() => { last(undefined); }).toThrow();
|
||||
});
|
||||
test('last() throws an Error', () => {
|
||||
expect(last()).toThrow();
|
||||
expect(() => { last(); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]);
|
||||
|
||||
@ -5,8 +5,8 @@ test('maxN is a Function', () => {
|
||||
expect(maxN).toBeInstanceOf(Function);
|
||||
});
|
||||
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', () => {
|
||||
expect(maxN([1, 2, 3], 2)).toEqual([3, 2])l
|
||||
expect(maxN([1, 2, 3], 2)).toEqual([3, 2]);
|
||||
});
|
||||
|
||||
@ -5,11 +5,11 @@ test('pipeAsyncFunctions is a Function', () => {
|
||||
expect(pipeAsyncFunctions).toBeInstanceOf(Function);
|
||||
});
|
||||
test('pipeAsyncFunctions result should be 15', () => {
|
||||
expect(await pipeAsyncFunctions(
|
||||
expect(pipeAsyncFunctions(
|
||||
(x) => x + 1,
|
||||
(x) => new Promise((resolve) => setTimeout(() => resolve(x + 2), 0)),
|
||||
(x) => x + 3,
|
||||
async (x) => await x + 4,
|
||||
)
|
||||
(5)).toBe(15);
|
||||
(5)).resolves.toBe(15);
|
||||
});
|
||||
|
||||
@ -11,19 +11,19 @@ test('quickSort([-1, 0, -2]) returns [-2, -1, 0]', () => {
|
||||
expect(quickSort([-1, 0, -2])).toEqual([-2, -1, 0]);
|
||||
});
|
||||
test('quickSort() throws an error', () => {
|
||||
expect(quickSort()).toThrow();
|
||||
expect(() => { quickSort(); }).toThrow();
|
||||
});
|
||||
test('quickSort(123) throws an error', () => {
|
||||
expect(quickSort(123)).toThrow();
|
||||
expect(() => { quickSort(123); }).toThrow();
|
||||
});
|
||||
test('quickSort({ 234: string}) throws an error', () => {
|
||||
expect(quickSort({ 234: string})).toThrow();
|
||||
expect(() => { quickSort({ 234: string}); }).toThrow();
|
||||
});
|
||||
test('quickSort(null) throws an error', () => {
|
||||
expect(quickSort(null)).toThrow();
|
||||
expect(() => { quickSort(null); }).toThrow();
|
||||
});
|
||||
test('quickSort(undefined) throws an error', () => {
|
||||
expect(quickSort(undefined)).toThrow();
|
||||
expect(() => { quickSort(undefined); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
quickSort([11, 1, 324, 23232, -1, 53, 2, 524, 32, 13, 156, 133, 62, 12, 4]);
|
||||
|
||||
@ -7,5 +7,5 @@ test('runPromisesInSeries is a Function', () => {
|
||||
});
|
||||
const delay = d => new Promise(r => setTimeout(r, d));
|
||||
test('Runs promises in series', () => {
|
||||
runPromisesInSeries([() => delay(100), () => delay(200).then(() => expect(true).toBeTruthy()));
|
||||
runPromisesInSeries([() => delay(100), () => delay(200).then(() => expect(true).toBeTruthy())]);
|
||||
});
|
||||
|
||||
@ -6,7 +6,9 @@ test('shallowClone is a Function', () => {
|
||||
});
|
||||
const a = { foo: 'bar', obj: { a: 1, b: 2 } };
|
||||
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', () => {
|
||||
expect(a.obj).toBe(b.obj);
|
||||
});
|
||||
|
||||
@ -5,7 +5,7 @@ test('stringPermutations is a Function', () => {
|
||||
expect(stringPermutations).toBeInstanceOf(Function);
|
||||
});
|
||||
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', () => {
|
||||
expect(stringPermutations('a')).toEqual(['a']);
|
||||
|
||||
@ -5,7 +5,7 @@ test('tail is a Function', () => {
|
||||
expect(tail).toBeInstanceOf(Function);
|
||||
});
|
||||
test('Returns tail', () => {
|
||||
expect(tail([1, 2, 3]), [2).toEqual(3]);
|
||||
expect(tail([1, 2, 3])).toEqual([2, 3]);
|
||||
});
|
||||
test('Returns tail', () => {
|
||||
expect(tail([1])).toEqual([1]);
|
||||
|
||||
@ -5,8 +5,8 @@ test('take is a Function', () => {
|
||||
expect(take).toBeInstanceOf(Function);
|
||||
});
|
||||
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.', () => {
|
||||
expect(take([1, 2, 3], 0)).toEqual([])
|
||||
expect(take([1, 2, 3], 0)).toEqual([]);
|
||||
});
|
||||
|
||||
1997
test/testlog
1997
test/testlog
File diff suppressed because it is too large
Load Diff
@ -4,29 +4,29 @@ const toCamelCase = require('./toCamelCase.js');
|
||||
test('toCamelCase is a 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');
|
||||
});
|
||||
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');
|
||||
});
|
||||
test('toCamelCase('some-javascript-property') return someJavascriptProperty', () => {
|
||||
test('toCamelCase(\'some-javascript-property\') return 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');
|
||||
});
|
||||
test('toCamelCase() throws a error', () => {
|
||||
expect(toCamelCase()).toThrow();
|
||||
expect(() => {toCamelCase(); }).toThrow();
|
||||
});
|
||||
test('toCamelCase([]) throws a error', () => {
|
||||
expect(toCamelCase([])).toThrow();
|
||||
expect(() => {toCamelCase([]); }).toThrow();
|
||||
});
|
||||
test('toCamelCase({}) throws a error', () => {
|
||||
expect(toCamelCase({})).toThrow();
|
||||
expect(() => {toCamelCase({}); }).toThrow();
|
||||
});
|
||||
test('toCamelCase(123) throws a error', () => {
|
||||
expect(toCamelCase(123)).toThrow();
|
||||
expect(() => {toCamelCase(123); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');
|
||||
|
||||
@ -5,11 +5,11 @@ test('toCurrency is a Function', () => {
|
||||
expect(toCurrency).toBeInstanceOf(Function);
|
||||
});
|
||||
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)', () => {
|
||||
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', () => {
|
||||
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));
|
||||
});
|
||||
|
||||
@ -20,13 +20,13 @@ test('toKebabCase() returns undefined', () => {
|
||||
expect(toKebabCase()).toBe(undefined)
|
||||
});
|
||||
test('toKebabCase([]) throws an erro', () => {
|
||||
expect(toKebabCase([])).toThrow();
|
||||
expect(() => { toKebabCase([]); }).toThrow();
|
||||
});
|
||||
test('toKebabCase({}) throws an erro', () => {
|
||||
expect(toKebabCase({})).toThrow();
|
||||
expect(() => { toKebabCase({}); }).toThrow();
|
||||
});
|
||||
test('toKebabCase(123) throws an erro', () => {
|
||||
expect(toKebabCase(123)).toThrow();
|
||||
expect(() => { toKebabCase(123); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML');
|
||||
|
||||
@ -10,7 +10,7 @@ test('Number(toSafeInteger(3.2)) is a number', () => {
|
||||
test('Converts a value to a safe integer', () => {
|
||||
expect(toSafeInteger(3.2)).toBe(3);
|
||||
});
|
||||
test('toSafeInteger('4.2') returns 4', () => {
|
||||
test('toSafeInteger(\'4.2\') returns 4', () => {
|
||||
expect(toSafeInteger('4.2')).toBe(4);
|
||||
});
|
||||
test('toSafeInteger(4.6) returns 5', () => {
|
||||
@ -22,7 +22,7 @@ test('toSafeInteger([]) returns 0', () => {
|
||||
test('isNaN(toSafeInteger([1.5, 3124])) is true', () => {
|
||||
expect(isNaN(toSafeInteger([1.5, 3124]))).toBeTruthy();
|
||||
});
|
||||
test('isNaN(toSafeInteger('string')) is true', () => {
|
||||
test('isNaN(toSafeInteger(\'string\')) is true', () => {
|
||||
expect(isNaN(toSafeInteger('string'))).toBeTruthy();
|
||||
});
|
||||
test('isNaN(toSafeInteger({})) is true', () => {
|
||||
|
||||
@ -4,7 +4,7 @@ const toSnakeCase = require('./toSnakeCase.js');
|
||||
test('toSnakeCase is a Function', () => {
|
||||
expect(toSnakeCase).toBeInstanceOf(Function);
|
||||
});
|
||||
test('toSnakeCase('\camelCase\') returns camel_case', () => {
|
||||
test('toSnakeCase(\'camelCase\') returns camel_case', () => {
|
||||
expect(toSnakeCase('camelCase')).toBe('camel_case');
|
||||
});
|
||||
test('toSnakeCase(\'some text\') returns some_text', () => {
|
||||
@ -20,13 +20,13 @@ test('toSnakeCase() returns undefined', () => {
|
||||
expect(toSnakeCase()).toBe(undefined);
|
||||
});
|
||||
test('toSnakeCase([]) throws an error', () => {
|
||||
expect(toSnakeCase([])).toThrow();
|
||||
expect(() => {toSnakeCase([]);}).toThrow();
|
||||
});
|
||||
test('toSnakeCase({}) throws an error', () => {
|
||||
expect(toSnakeCase({})).toThrow();
|
||||
expect(() => {toSnakeCase({});}).toThrow();
|
||||
});
|
||||
test('toSnakeCase(123) throws an error', () => {
|
||||
expect(toSnakeCase(123)).toThrow();
|
||||
expect(() => {toSnakeCase(123);}).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML');
|
||||
|
||||
@ -10,5 +10,5 @@ test('Transforms an object', () => {
|
||||
(r, v, k) => {
|
||||
(r[v] || (r[v] = [])).push(k);
|
||||
return r;
|
||||
},{}).toEqual({ '1': ['a', 'c'], '2': ['b'] });
|
||||
},{})).toEqual({ '1': ['a', 'c'], '2': ['b'] });
|
||||
});
|
||||
|
||||
@ -7,7 +7,7 @@ test('union is a Function', () => {
|
||||
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]);
|
||||
});
|
||||
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' ]);
|
||||
});
|
||||
test('union([[], {}], [1, 2, 3]) returns [[], {}, 1, 2, 3]', () => {
|
||||
@ -17,22 +17,22 @@ test('union([], []) returns []', () => {
|
||||
expect(union([], [])).toEqual([]);
|
||||
});
|
||||
test('union() throws an error', () => {
|
||||
expect(union()).toThrow();
|
||||
expect(() => {union(); }).toThrow();
|
||||
});
|
||||
test('union(true, \'str\') throws an error', () => {
|
||||
expect(union(true, 'str')).toThrow();
|
||||
expect(() => {union(true, 'str'); }).toThrow();
|
||||
});
|
||||
test('union(\'false\', true) throws an error', () => {
|
||||
expect(union('false', true)).toThrow();
|
||||
expect(() => {union('false', true); }).toThrow();
|
||||
});
|
||||
test('union((123, {}) throws an error', () => {
|
||||
expect(union((123, {})).toThrow();
|
||||
expect(() => {union(123, {}); }).toThrow();
|
||||
});
|
||||
test('union([], {}) throws an error', () => {
|
||||
expect(union([], {})).toThrow();
|
||||
expect(() => {union([], {}); }).toThrow();
|
||||
});
|
||||
test('union(undefined, null) throws an error', () => {
|
||||
expect(union(undefined, null)).toThrow();
|
||||
expect(() => {union(undefined, null); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
union([1, 2, 3], [4, 3, 2]);
|
||||
|
||||
@ -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]', () => {
|
||||
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, '']);
|
||||
});
|
||||
test('uniqueElements() returns []', () => {
|
||||
@ -23,20 +23,20 @@ test('uniqueElements(null) returns []', () => {
|
||||
test('uniqueElements(undefined) returns []', () => {
|
||||
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']);
|
||||
});
|
||||
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', () => {
|
||||
expect(uniqueElements({})).toThrow();
|
||||
expect(() => {uniqueElements({}); }).toThrow();
|
||||
});
|
||||
test('uniqueElements(true) throws an error', () => {
|
||||
expect(uniqueElements(true)).toThrow();
|
||||
expect(() => {uniqueElements(true); }).toThrow();
|
||||
});
|
||||
test('uniqueElements(false) throws an error', () => {
|
||||
expect(uniqueElements(false)).toThrow();
|
||||
expect(() => {uniqueElements(false); }).toThrow();
|
||||
});
|
||||
let start = new Date().getTime();
|
||||
uniqueElements([true, 0, 1, false, false, undefined, null, '']);
|
||||
|
||||
@ -5,8 +5,8 @@ test('unzip is a Function', () => {
|
||||
expect(unzip).toBeInstanceOf(Function);
|
||||
});
|
||||
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]]', () => {
|
||||
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]]);
|
||||
});
|
||||
|
||||
@ -5,5 +5,5 @@ test('unzipWith is a 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]', () => {
|
||||
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]);
|
||||
});
|
||||
|
||||
@ -10,24 +10,24 @@ test('without([2, 1, 2, 3], 1, 2) returns [3]', () => {
|
||||
test('without([]) returns []', () => {
|
||||
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]);
|
||||
});
|
||||
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']);
|
||||
});
|
||||
test('without() throws an error', () => {
|
||||
expect(without()).toThrow();
|
||||
expect(() => { without(); }).toThrow();
|
||||
});
|
||||
test('without(null) throws an error', () => {
|
||||
expect(without(null)).toThrow();
|
||||
expect(() => { without(null); }).toThrow();
|
||||
});
|
||||
test('without(undefined) throws an error', () => {
|
||||
expect(without(undefined)).toThrow();
|
||||
expect(() => { without(undefined); }).toThrow();
|
||||
});
|
||||
test('without(123) throws an error', () => {
|
||||
expect(without(123)).toThrow();
|
||||
expect(() => { without(123); }).toThrow();
|
||||
});
|
||||
test('without({}) throws an error', () => {
|
||||
expect(without({})).toThrow();
|
||||
expect(() => { without({}); }).toThrow();
|
||||
});
|
||||
|
||||
@ -4,30 +4,30 @@ const words = require('./words.js');
|
||||
test('words is a 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"]);
|
||||
});
|
||||
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"]);
|
||||
});
|
||||
test('words(I love javaScript!!) returns an array', () => {
|
||||
expect(Array.isArray(words('I love javaScript!!'))).toBeTruthy();
|
||||
});
|
||||
test('words() throws an error', () => {
|
||||
expect(words()).toThrow();
|
||||
expect(() => { words(); }).toThrow();
|
||||
});
|
||||
test('words(null) throws an error', () => {
|
||||
expect(words(null)).toThrow();
|
||||
expect(() => { words(null); }).toThrow();
|
||||
});
|
||||
test('words(undefined) throws an error', () => {
|
||||
expect(words(undefined)).toThrow();
|
||||
expect(() => { words(undefined); }).toThrow();
|
||||
});
|
||||
test('words({}) throws an error', () => {
|
||||
expect(words({})).toThrow();
|
||||
expect(() => { words({}); }).toThrow();
|
||||
});
|
||||
test('words([]) throws an error', () => {
|
||||
expect(words([])).toThrow();
|
||||
expect(() => { words([]); }).toThrow();
|
||||
});
|
||||
test('words(1234) throws an error', () => {
|
||||
expect(words(1234)).toThrow();
|
||||
expect(() => { words(1234); }).toThrow();
|
||||
});
|
||||
|
||||
@ -24,8 +24,8 @@ test('zip([a], [1, 2], [true, false]) returns an Array', () => {
|
||||
expect(Array.isArray(zip(['a'], [1, 2], [true, false]))).toBeTruthy();
|
||||
});
|
||||
test('zip(null) throws an error', () => {
|
||||
expect(zip(null)).toThrow();
|
||||
expect(() => {zip(null);}).toThrow();
|
||||
});
|
||||
test('zip(undefined) throws an error', () => {
|
||||
expect(zip(undefined)).toThrow();
|
||||
expect(() => {zip(undefined);}).toThrow();
|
||||
});
|
||||
|
||||
@ -17,17 +17,17 @@ test('zipObject([a], string) returns { a: s }', () => {
|
||||
expect(zipObject(['a'], 'string')).toEqual({ a: 's' });
|
||||
});
|
||||
test('zipObject() throws an error', () => {
|
||||
expect(zipObject()).toThrow();
|
||||
expect(() => {zipObject();}).toThrow();
|
||||
});
|
||||
test('zipObject(([\'string\'], null) throws an error', () => {
|
||||
expect(zipObject((['string'], null)).toThrow();
|
||||
expect(() => {zipObject(['string'], null);}).toThrow();
|
||||
});
|
||||
test('zipObject(null, [1]) throws an error', () => {
|
||||
expect(zipObject(null, [1])).toThrow();
|
||||
expect(() => {zipObject(null, [1]);}).toThrow();
|
||||
});
|
||||
test('zipObject(\'string\') throws an error', () => {
|
||||
expect(zipObject('string')).toThrow();
|
||||
expect(() => {zipObject('string');}).toThrow();
|
||||
});
|
||||
test('zipObject(\'test\', \'string\') throws an error', () => {
|
||||
expect(zipObject('test', 'string')).toThrow();
|
||||
expect(() => {zipObject('test', 'string');}).toThrow();
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user