From 2ab118d70e32b4afdb9310e3b5d2d7535cbbc00a Mon Sep 17 00:00:00 2001 From: Bladymir Tellez Date: Sun, 1 Apr 2018 19:31:50 -0500 Subject: [PATCH] let all of the things --- bin/help_menu.js | 4 +- bin/mockingjays.js | 4 +- bin/option_parser.js | 18 +++--- .../cache_header_options_steps.js | 28 ++++----- features/step_definitions/form_data_steps.js | 20 +++---- .../minimal_mockingjay_steps.js | 2 +- .../request_response_log_steps.js | 4 +- .../stateful_requests_steps.js | 12 ++-- features/support/hooks.js | 6 +- features/support/test_server.js | 12 ++-- features/support/world.js | 10 ++-- index.js | 14 ++--- src/cache_client.js | 32 +++++----- src/colorize.js | 2 +- src/default_options.js | 38 ++++++------ src/filesystem_helper.js | 8 +-- src/form_data.js | 30 +++++----- src/header_util.js | 34 +++++------ src/http_client.js | 24 ++++---- src/logger.js | 20 +++---- src/mockingjay.js | 30 +++++----- src/rehasher.js | 20 +++---- src/request_hash.js | 8 +-- src/server.js | 2 +- src/transaction_state.js | 10 ++-- src/util.js | 16 ++--- test/cache_client_spec.js | 6 +- test/default_options_spec.js | 18 +++--- test/form_data_spec.js | 16 ++--- test/header_util_spec.js | 52 ++++++++--------- test/http_client_spec.js | 2 +- test/mockingjay_spec.js | 4 +- test/option_parser_spec.js | 4 +- test/request_hash_spec.js | 58 +++++++++---------- test/transaction_state_spec.js | 10 ++-- test/util_spec.js | 26 ++++----- 36 files changed, 302 insertions(+), 302 deletions(-) diff --git a/bin/help_menu.js b/bin/help_menu.js index 15b793d..a19a4db 100644 --- a/bin/help_menu.js +++ b/bin/help_menu.js @@ -1,5 +1,5 @@ -var HelpMenu = function() { - var helpDescription = [ +let HelpMenu = function() { + let helpDescription = [ "", "Usage:", " mockingjays [options]", diff --git a/bin/mockingjays.js b/bin/mockingjays.js index 99d361b..f621dbb 100755 --- a/bin/mockingjays.js +++ b/bin/mockingjays.js @@ -3,7 +3,7 @@ import Mockingjays from '../index'; import HelpMenu from './help_menu'; import OptionParser from './option_parser'; -var userOptions = OptionParser.parse(process.argv); +let userOptions = OptionParser.parse(process.argv); switch (true) { case OptionParser.shouldDisplayHelp(userOptions): @@ -21,4 +21,4 @@ switch (true) { default: console.log('Error Parsing Options. Expected: serve, rehash, --help, or --version'); HelpMenu(); -} \ No newline at end of file +} diff --git a/bin/option_parser.js b/bin/option_parser.js index d677fbd..6fd3eb6 100644 --- a/bin/option_parser.js +++ b/bin/option_parser.js @@ -1,21 +1,21 @@ import parseArgs from 'minimist'; import _ from 'lodash'; -var OptionsParser = {} +let OptionsParser = {} -var hasCommand = (arg) => arg == 'serve' || arg == 'rehash' +let hasCommand = (arg) => arg == 'serve' || arg == 'rehash' OptionsParser.parse = function(processArgs) { - var userArgs = parseArgs(processArgs.slice(2)); - var command = _.find(userArgs._, hasCommand) + let userArgs = parseArgs(processArgs.slice(2)); + let command = _.find(userArgs._, hasCommand) delete userArgs._ // Argument are parse. Done Extracting Values return _.extend(userArgs, {command: command}) } OptionsParser.shouldDisplayHelp = function (options) { - var argCount = 0; - for (var key in options) { + let argCount = 0; + for (let key in options) { argCount++; } return options.command == 'help' || options.help || argCount == 0; @@ -33,9 +33,9 @@ OptionsParser.shouldRehash = function (options) { OptionsParser.shouldServe = function (options) { - var displayHelpMenu = OptionsParser.shouldDisplayHelp(options); - var displayVersionNumber = OptionsParser.shouldDisplayVersion(options); - var rehash = OptionsParser.shouldRehash(options); + let displayHelpMenu = OptionsParser.shouldDisplayHelp(options); + let displayVersionNumber = OptionsParser.shouldDisplayVersion(options); + let rehash = OptionsParser.shouldRehash(options); return !displayHelpMenu && !displayVersionNumber && !rehash; } diff --git a/features/step_definitions/cache_header_options_steps.js b/features/step_definitions/cache_header_options_steps.js index 028791e..fef8629 100644 --- a/features/step_definitions/cache_header_options_steps.js +++ b/features/step_definitions/cache_header_options_steps.js @@ -7,11 +7,11 @@ import {Then, When} from 'cucumber'; const TIMEOUT = 20 * 1000; When(/^I make a "([^"]*)" request to "([^"]*)" with headers:$/, {timeout: TIMEOUT}, function (method, urlPath, table, done) { - var headers = {}; + let headers = {}; table.rows().forEach(row => headers[row[0]] = row[1]); - var options = { + let options = { hostname: 'localhost', port: this.options.port, path: urlPath, @@ -19,8 +19,8 @@ When(/^I make a "([^"]*)" request to "([^"]*)" with headers:$/, {timeout: TIMEOU headers: headers }; - var req = http.request(options, (response) => { - var chunks = []; + let req = http.request(options, (response) => { + let chunks = []; response.on('data', (chunk) => { chunks.push(chunk); }); @@ -40,24 +40,24 @@ When(/^I make a "([^"]*)" request to "([^"]*)" with headers:$/, {timeout: TIMEOU When(/^I make a GET request to "([^"]*)" with the query strings:$/, function (path, table, done) { - var first = true; - var queryString = table.hashes().reduce(function(qs, current) { - var key = current.KEY; - var val = current.VALUE; + let first = true; + let queryString = table.hashes().reduce(function(qs, current) { + let key = current.KEY; + let val = current.VALUE; qs += (first ? '' : '&') + key + '=' + (isNaN(val) ? val : parseInt(val, 10)); first = false; return qs; }, '?'); - var options = { + let options = { hostname: 'localhost', port: this.options.port, path: path + queryString, method: 'GET' }; - var req = http.request(options, function(response) { - var str = ''; + let req = http.request(options, function(response) { + let str = ''; response.on('data', function (chunk) {str += chunk;}); response.on('end', function() { this.result = str; @@ -71,14 +71,14 @@ When(/^I make a GET request to "([^"]*)" with the query strings:$/, function (pa Then(/^I see a cache file for "([^"]*)" with the following headers:$/, function (path, table, done) { - var files = this.cacheFiles(this.options.cacheDir, path); + let files = this.cacheFiles(this.options.cacheDir, path); if (files.length != 1) { done('Expecting 1 file for form-data. '+ files.length +' found'); return; } - var generatedJSON = JSON.parse(fs.readFileSync(files[0], {encoding: 'utf-8'})); - var requiredHeadersFound = true; + let generatedJSON = JSON.parse(fs.readFileSync(files[0], {encoding: 'utf-8'})); + let requiredHeadersFound = true; table.rows().forEach(function(row) { requiredHeadersFound = requiredHeadersFound diff --git a/features/step_definitions/form_data_steps.js b/features/step_definitions/form_data_steps.js index c3f6e6a..d64e42b 100644 --- a/features/step_definitions/form_data_steps.js +++ b/features/step_definitions/form_data_steps.js @@ -9,13 +9,13 @@ When(/^I wait$/, {timeout: 60 * 1000 * 5}, function () { When(/^I make a form data request to "([^"]*)"$/, function (path, done) { - var postData = '--AaB03x\r\n' + + let postData = '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Hello World\r\n' + '--AaB03x--\r\n'; - var options = { + let options = { hostname: 'localhost', port: this.options.port, path: path, @@ -25,8 +25,8 @@ When(/^I make a form data request to "([^"]*)"$/, function (path, done) { method: 'POST' }; - var req = http.request(options, function(response) { - var str = ''; + let req = http.request(options, function(response) { + let str = ''; response.on('data', function (chunk) {str += chunk;}); response.on('end', function() { this.result = str; @@ -40,19 +40,19 @@ When(/^I make a form data request to "([^"]*)"$/, function (path, done) { Then(/^the boundary is a mockingjays boundary$/, function (done) { - var files = this.cacheFiles(this.options.cacheDir, '/formData'); + let files = this.cacheFiles(this.options.cacheDir, '/formData'); if (files.length != 1) { done('Expecting 1 file for form-data. '+ files.length +' found'); return; } - var generatedJSON = JSON.parse(fs.readFileSync(files[0], {encoding: 'utf-8'})); - var hasUpdatedBoundary = generatedJSON.request.body.match('mockingjay'); + let generatedJSON = JSON.parse(fs.readFileSync(files[0], {encoding: 'utf-8'})); + let hasUpdatedBoundary = generatedJSON.request.body.match('mockingjay'); done(!hasUpdatedBoundary ? 'Missing Mockingjays Boundary in Form Data': null); }); When(/^I make a POST request to "([^"]*)" with the JSON body:$/, function (path, postData, done) { - var options = { + let options = { hostname: 'localhost', port: this.options.port, path: path, @@ -62,8 +62,8 @@ When(/^I make a POST request to "([^"]*)" with the JSON body:$/, function (path, method: 'POST' } - var req = http.request(options, function(response) { - var str = ''; + let req = http.request(options, function(response) { + let str = ''; response.on('data', function(chunk) {str += chunk;}); response.on('end', function() { this.result = str; diff --git a/features/step_definitions/minimal_mockingjay_steps.js b/features/step_definitions/minimal_mockingjay_steps.js index 44c5967..06df93a 100644 --- a/features/step_definitions/minimal_mockingjay_steps.js +++ b/features/step_definitions/minimal_mockingjay_steps.js @@ -9,7 +9,7 @@ Given(/^I want to create a Mockingjay instance with no options$/, function (done Given(/^I want to create a Mockingjay instance with the following options$/, function (optionsTable, done) { - var options = {} + let options = {} optionsTable.rows().forEach(function (row) { return options[row[0]] = row[1]; }); diff --git a/features/step_definitions/request_response_log_steps.js b/features/step_definitions/request_response_log_steps.js index 75471e3..f4da02f 100644 --- a/features/step_definitions/request_response_log_steps.js +++ b/features/step_definitions/request_response_log_steps.js @@ -1,6 +1,6 @@ import {When} from 'cucumber'; When(/^I can see the log file "([^"]*)"$/, function (logFileName, done) { - var files = this.logFile(this.options.cacheDir, logFileName); + let files = this.logFile(this.options.cacheDir, logFileName); done(files.length ? undefined : 'Expected to see log file:' + logFileName + ", but found "+ files.length + " files"); -}); \ No newline at end of file +}); diff --git a/features/step_definitions/stateful_requests_steps.js b/features/step_definitions/stateful_requests_steps.js index 81d6d6b..b46ce5f 100644 --- a/features/step_definitions/stateful_requests_steps.js +++ b/features/step_definitions/stateful_requests_steps.js @@ -12,15 +12,15 @@ Given(/^I provide the following transition config$/, function (string, done) { When(/^I make a "([^"]*)" request to "([^"]*)"$/, function (method, path, done) { - var options = { + let options = { hostname: 'localhost', port: this.options.port, path: path, method: method } - var req = http.request(options, (response) => { - var str = ''; + let req = http.request(options, (response) => { + let str = ''; response.on('data', (chunk) => {str += chunk;}); response.on('end', () => { this.result = str; @@ -34,17 +34,17 @@ When(/^I make a "([^"]*)" request to "([^"]*)"$/, function (method, path, done) Then(/^I can see (\d+) cache files for "([^"]*)"$/, function (count, path, done) { - var files = this.cacheFiles(this.options.cacheDir, path); + let files = this.cacheFiles(this.options.cacheDir, path); done(files.length == parseInt(count, 10) ? undefined : 'Expected to see ' + count + " cache files, but found "+ files.length); }); Then(/^I see the result "([^"]*)"$/, function (result, done) { - var msg = [ + let msg = [ 'Expected Result Not Found', 'Expected: ' + result, 'Found: ' + this.result ].join('\n'); done(this.result.indexOf(result) > -1 ? undefined : msg); -}); \ No newline at end of file +}); diff --git a/features/support/hooks.js b/features/support/hooks.js index a3ec569..b9397c6 100644 --- a/features/support/hooks.js +++ b/features/support/hooks.js @@ -3,7 +3,7 @@ import fs from 'fs'; import TestServer from './test_server'; Before('@TestServer', async function (scenario) { - var world = this; + let world = this; world.serverState = {count: 0}; world.server = await TestServer(); @@ -41,7 +41,7 @@ Before('@TestServer', async function (scenario) { After('@TestServer', function (scenario) { - var world = this; + let world = this; world.serverState.count = 0; world.server.stop(); -}); \ No newline at end of file +}); diff --git a/features/support/test_server.js b/features/support/test_server.js index 012f2c8..73b1fed 100644 --- a/features/support/test_server.js +++ b/features/support/test_server.js @@ -1,17 +1,17 @@ import Hapi from 'hapi'; import inert from 'inert'; -var TestServerBuilder = async function(options){ +let TestServerBuilder = async function(options){ options = options || {}; - var userHost = options.host || 'localhost'; - var userPort = options.port || 9001; - var hapiInstance = new Hapi.server({host: userHost, port: userPort}); + let userHost = options.host || 'localhost'; + let userPort = options.port || 9001; + let hapiInstance = new Hapi.server({host: userHost, port: userPort}); await hapiInstance.register(inert); return new TestServer(hapiInstance); }; -var TestServer = function(server){ +let TestServer = function(server){ this.state = {}; this.server = server; }; @@ -33,7 +33,7 @@ TestServer.prototype.stop = function () { }; TestServer.prototype.start = function () { - var self = this; + let self = this; this.server.start((err) => { if (err) { throw err; } }); diff --git a/features/support/world.js b/features/support/world.js index 8201252..b250201 100644 --- a/features/support/world.js +++ b/features/support/world.js @@ -4,17 +4,17 @@ import path from 'path'; function World() { this.cacheFiles = function(cacheDir, endpoint) { - var cwd = process.cwd(); + let cwd = process.cwd(); endpoint = endpoint.toLowerCase() - var isFile = function (filePath) { return !FileSystemHelper.directoryExists(filePath); }; + let isFile = function (filePath) { return !FileSystemHelper.directoryExists(filePath); }; return FileSystemHelper.findFileType(path.join(cwd, cacheDir, endpoint), isFile); } this.logFile = function(cacheDir, logFile) { - var cwd = process.cwd(); - var isFile = function (filePath) { return filePath.indexOf(logFile) > -1;}; + let cwd = process.cwd(); + let isFile = function (filePath) { return filePath.indexOf(logFile) > -1;}; return FileSystemHelper.findFileType(path.join(cwd, cacheDir), isFile); } } -setWorldConstructor(World) \ No newline at end of file +setWorldConstructor(World) diff --git a/index.js b/index.js index eda2e4e..25f0e6e 100644 --- a/index.js +++ b/index.js @@ -3,7 +3,7 @@ import Mockingjay from './src/mockingjay'; import Rehasher from './src/rehasher'; import DefaultOptions from './src/default_options'; -var Mockingjays = function() {} +let Mockingjays = function() {} /** * Start creates a Mockingjays Server and starts proxying @@ -16,10 +16,10 @@ var Mockingjays = function() {} * @param onReady - A {Function} to be called when the proxy is ready. [Optional] */ Mockingjays.prototype.start = function(options, onReady) { - var defaultOptions = new DefaultOptions(); - var finalOptions = defaultOptions.merge(options); - var mockingjay = new Mockingjay(finalOptions); - var requestHandler = function(req, res) { + let defaultOptions = new DefaultOptions(); + let finalOptions = defaultOptions.merge(options); + let mockingjay = new Mockingjay(finalOptions); + let requestHandler = function(req, res) { mockingjay.onRequest(req, res); }; this.server = Server.listen(finalOptions, requestHandler, onReady); @@ -39,8 +39,8 @@ Mockingjays.prototype.close = function(done) { * :serverBaseUrl - Base URL for the source server. */ Mockingjays.prototype.rehash = function(options) { - var defaultOptions = new DefaultOptions(); - var finalOptions = defaultOptions.merge(options, {attemptToCreateCacheDir: false}); + let defaultOptions = new DefaultOptions(); + let finalOptions = defaultOptions.merge(options, {attemptToCreateCacheDir: false}); new Rehasher(finalOptions).process(); } diff --git a/src/cache_client.js b/src/cache_client.js index df91645..8d5ca16 100644 --- a/src/cache_client.js +++ b/src/cache_client.js @@ -12,7 +12,7 @@ const RW_MODE = fs.F_OK | fs.R_OK | fs.W_OK; const EXT = '.json'; let replaceQueryParam = function(directoryName) { - var queryParamStartIndex = directoryName.indexOf('?'); + let queryParamStartIndex = directoryName.indexOf('?'); if (queryParamStartIndex == -1){ return directoryName; @@ -21,7 +21,7 @@ let replaceQueryParam = function(directoryName) { return directoryName.substr(0, queryParamStartIndex); } -var CacheClient = function(options) { +let CacheClient = function(options) { this.logger = options.logger; this.passthrough = options.passthrough; this.cacheDir = options.cacheDir; @@ -97,7 +97,7 @@ CacheClient.prototype.writeToAccessFile = function (filePath) { CacheClient.prototype.fetch = function (request) { - var filePath = this.getReadFileName(request); + let filePath = this.getReadFileName(request); this.logger.debug(Colorize.blue('Serving'), filePath); this.writeToAccessFile(filePath); return new Promise((resolve, reject) => { @@ -113,11 +113,11 @@ CacheClient.prototype.record = function (request, response) { return new Promise((resolve, reject) => { response.request.headers = HeaderUtil.filterHeaders(this.cacheHeader, request.headers); response.headers = HeaderUtil.removeHeaders(this.responseHeaderBlacklist, response.headers); - var responseString = Util.stringify(response) + "\n"; + let responseString = Util.stringify(response) + "\n"; - var writeToFile = () => { + let writeToFile = () => { if (this.passthrough) {return resolve(response);} - var targetFile = this.getWriteFileName(request); + let targetFile = this.getWriteFileName(request); this.writeToAccessFile(targetFile); fs.writeFile(targetFile, responseString, (err) => { if (err) {return reject(err);} @@ -125,7 +125,7 @@ CacheClient.prototype.record = function (request, response) { }); }; - var directory = this.directory(request, this.overrideCacheDir || this.cacheDir); + let directory = this.directory(request, this.overrideCacheDir || this.cacheDir); if (!FileSystemHelper.directoryExists(directory)) { return FileSystemHelper.createDirectory(directory).then(writeToFile); } @@ -136,15 +136,15 @@ CacheClient.prototype.record = function (request, response) { CacheClient.prototype.remove = function (request, originalFilename) { return new Promise((resolve, reject) => { - var directory = this.directory(request, this.cacheDir); + let directory = this.directory(request, this.cacheDir); if (FileSystemHelper.directoryExists(directory)) { - var filePath = originalFilename ? originalFilename : this.getReadFileName(request); + let filePath = originalFilename ? originalFilename : this.getReadFileName(request); fs.unlink(filePath, (error) => { if (!error) { return resolve(); } - var message = 'Unable to Delete File: ' + filePath; + let message = 'Unable to Delete File: ' + filePath; this.logger.error(message, error); return reject(error) }); @@ -157,8 +157,8 @@ CacheClient.prototype.remove = function (request, originalFilename) { CacheClient.prototype.directory = function (request, rootDir) { - var requestPath = request.path || ''; - var pathEndsSlash = requestPath.lastIndexOf('/') == path.length - 1 + let requestPath = request.path || ''; + let pathEndsSlash = requestPath.lastIndexOf('/') == path.length - 1 requestPath = pathEndsSlash ? requestPath.substr(0, requestPath.length - 1) : requestPath; requestPath = requestPath.split('/').map(replaceQueryParam).join('/').toLowerCase(); @@ -167,16 +167,16 @@ CacheClient.prototype.directory = function (request, rootDir) { CacheClient.prototype.requestPathOverride = function (request) { - var requestHash = this.requestHash(request); - var directory = this.directory(request, this.overrideCacheDir); + let requestHash = this.requestHash(request); + let directory = this.directory(request, this.overrideCacheDir); return path.join(directory, requestHash) + EXT; } CacheClient.prototype.requestPath = function (request) { - var requestHash = this.requestHash(request); - var directory = this.directory(request, this.cacheDir); + let requestHash = this.requestHash(request); + let directory = this.directory(request, this.cacheDir); return path.join(directory, requestHash) + EXT; } diff --git a/src/colorize.js b/src/colorize.js index 336dbdc..f1542a2 100644 --- a/src/colorize.js +++ b/src/colorize.js @@ -1,4 +1,4 @@ -var Colorize = {}; +let Colorize = {}; Colorize.red = function(text) { return "\\033[1;31m" + text + "\\033[0m"; diff --git a/src/default_options.js b/src/default_options.js index d2e022d..9237900 100644 --- a/src/default_options.js +++ b/src/default_options.js @@ -5,9 +5,9 @@ import FileSystemHelper from './filesystem_helper'; import Logger from './logger'; import Util from './util'; -var logger = new Logger(); +let logger = new Logger(); -var getBooleanValue = function(value, defaultValue) { +let getBooleanValue = function(value, defaultValue) { if (typeof value === 'undefined') { return defaultValue; } @@ -19,8 +19,8 @@ var getBooleanValue = function(value, defaultValue) { // Handle String Values if (typeof value === 'string') { - var isTrueString = value.toLowerCase() == 'true'; - var isFalseString = value.toLowerCase() == 'false'; + let isTrueString = value.toLowerCase() == 'true'; + let isFalseString = value.toLowerCase() == 'false'; return isTrueString && !isFalseString; } @@ -32,7 +32,7 @@ var getBooleanValue = function(value, defaultValue) { /** * Provides default values and verifies that requied values are set. */ -var DefaultOptions = function() {} +let DefaultOptions = function() {} DefaultOptions.prototype.options = { accessLogFile: null, @@ -60,7 +60,7 @@ DefaultOptions.prototype.defaultExtras = { DefaultOptions.prototype.merge = function(options, extraOptions) { - var extras = extraOptions || this.defaultExtras; + let extras = extraOptions || this.defaultExtras; this._handleAccessLogFile(options); this._handleBaseCacheDirectoryDefault(options); this._handleBaseUrlDefault(options); @@ -82,13 +82,13 @@ DefaultOptions.prototype.merge = function(options, extraOptions) { DefaultOptions.prototype._handleAccessLogFile = function (options) { - var defaults = this.options; + let defaults = this.options; options.accessLogFile = options.accessLogFile || defaults.accessLogFile; } DefaultOptions.prototype._handleBaseCacheDirectoryDefault = function (options, extras) { - var defaults = this.options; + let defaults = this.options; // Directory where the cache files can be read from: options.overrideCacheDir = options.overrideCacheDir || defaults.overrideCacheDir; @@ -109,7 +109,7 @@ DefaultOptions.prototype._handleBaseCacheDirectoryDefault = function (options, DefaultOptions.prototype._handleBaseUrlDefault = function (options) { - var defaults = this.options; + let defaults = this.options; // The base URL of the server to proxy requests to. options.serverBaseUrl = options.serverBaseUrl || defaults.serverBaseUrl; @@ -120,7 +120,7 @@ DefaultOptions.prototype._handleBaseUrlDefault = function (options) { DefaultOptions.prototype._handleCacheHeaders = function (options) { - var defaults = this.options; + let defaults = this.options; if (options.cacheHeader && typeof(options.cacheHeader) === 'string') { options.cacheHeader = options.cacheHeader.split(',').map(function(header) { return header.toLowerCase() }); } else { @@ -130,7 +130,7 @@ DefaultOptions.prototype._handleCacheHeaders = function (options) { DefaultOptions.prototype._handleCacheDirectoryDefault = function (options, extras) { - var defaults = this.options; + let defaults = this.options; // Directory where the cache files can be read and written to: options.cacheDir = options.cacheDir || defaults.cacheDir; if (!options.cacheDir) { @@ -150,8 +150,8 @@ DefaultOptions.prototype._handleCacheDirectoryDefault = function (options, extra DefaultOptions.prototype._handleContentTypeDefault = function (options) { - var defaults = this.options; - var blacklist = (options.ignoreContentType || defaults.ignoreContentType) + let defaults = this.options; + let blacklist = (options.ignoreContentType || defaults.ignoreContentType) .split(',') .filter(function (type) {return type !== ''}) .map(function (type) {return type.trim();}) @@ -161,7 +161,7 @@ DefaultOptions.prototype._handleContentTypeDefault = function (options) { DefaultOptions.prototype._handleIgnoreJsonBodyPath = function (options) { - var defaults = this.options; + let defaults = this.options; if (options.ignoreJsonBodyPath && typeof(options.ignoreJsonBodyPath) == 'string') { options.ignoreJsonBodyPath = options.ignoreJsonBodyPath.split(','); } else { @@ -171,7 +171,7 @@ DefaultOptions.prototype._handleIgnoreJsonBodyPath = function (options) { DefaultOptions.prototype._handleLogLevel = function (options) { - var defaults = this.options; + let defaults = this.options; if (!options.logLevel) { options.logLevel = defaults.logLevel; } @@ -184,7 +184,7 @@ DefaultOptions.prototype._handlePassthrough = function (options) { DefaultOptions.prototype._handlePortDefault = function (options) { - var defaults = this.options; + let defaults = this.options; options.port = options.port || defaults.port; } @@ -200,13 +200,13 @@ DefaultOptions.prototype._handleRefreshDefault = function (options) { DefaultOptions.prototype._handleRequestResponseLogFile = function (options) { - var defaults = this.options; + let defaults = this.options; options.requestResponseLogFile = options.requestResponseLogFile || defaults.requestResponseLogFile; } DefaultOptions.prototype._handleResponseHeaders = function (options) { - var defaults = this.options; + let defaults = this.options; if (options.responseHeaderBlacklist && typeof(options.responseHeaderBlacklist) == 'string') { options.responseHeaderBlacklist = options.responseHeaderBlacklist.split(','); } else { @@ -216,7 +216,7 @@ DefaultOptions.prototype._handleResponseHeaders = function (options) { DefaultOptions.prototype._handleTransitionConfig = function (options) { - var defaults = this.options; + let defaults = this.options; if (!options.transitionConfig) { options.transitionConfig = defaults.transitionConfig; } else { diff --git a/src/filesystem_helper.js b/src/filesystem_helper.js index 3068e53..cc01212 100644 --- a/src/filesystem_helper.js +++ b/src/filesystem_helper.js @@ -2,9 +2,9 @@ import fs from 'fs'; import path from 'path'; import Logger from './logger'; -var joinArray = function (acc, next) {return acc.concat(next);}; +let joinArray = function (acc, next) {return acc.concat(next);}; -var FileSystemHelper = { +let FileSystemHelper = { logger: new Logger() }; @@ -20,7 +20,7 @@ FileSystemHelper.createDirectory = function (directoryPath) { return new Promise(function (resolve, reject) { FileSystemHelper.createDirectoryParent(directoryPath, function (error) { if (error) { - var errorMessage = 'Failed to Create Directory: ' + directoryPath; + let errorMessage = 'Failed to Create Directory: ' + directoryPath; FileSystemHelper.logger.error('Failed to Create Directory: ' + directoryPath, error); reject('Failed to Create Directory: ' + directoryPath); } else { @@ -43,7 +43,7 @@ FileSystemHelper.createDirectoryParent = function (directoryPath, callback) { } FileSystemHelper.findFileType = function (root, typePredicate) { - var formattedRoot = root.lastIndexOf('/') != root.length - 1 ? root + '/' : root; + let formattedRoot = root.lastIndexOf('/') != root.length - 1 ? root + '/' : root; try { return fs .readdirSync(formattedRoot) diff --git a/src/form_data.js b/src/form_data.js index d3880e7..2150b19 100644 --- a/src/form_data.js +++ b/src/form_data.js @@ -1,13 +1,13 @@ import crypto from 'crypto'; import Util from './util'; -var FORM_MULTIPART = 'multipart/form-data'; -var FORM_URL_ENCODED = 'application/x-www-form-urlencoded'; -var CONTENT_TYPE = 'content-type'; -var CONTENT_LENGTH = 'content-length'; +let FORM_MULTIPART = 'multipart/form-data'; +let FORM_URL_ENCODED = 'application/x-www-form-urlencoded'; +let CONTENT_TYPE = 'content-type'; +let CONTENT_LENGTH = 'content-length'; -var FormDataHandler = {} +let FormDataHandler = {} FormDataHandler.isFormData = function (headers) { @@ -17,28 +17,28 @@ FormDataHandler.isFormData = function (headers) { FormDataHandler.getBoundary = function (contentType) { - var matches = contentType.match(/.*boundary="?([^"]*)"?/); + let matches = contentType.match(/.*boundary="?([^"]*)"?/); return matches[1] || ''; } FormDataHandler.getBodySignature = function (boundary, body) { - var strippedBody = body.replace(new RegExp(boundary, 'g'), '-'); - var signature = FormDataHandler.boundaryHash(strippedBody); + let strippedBody = body.replace(new RegExp(boundary, 'g'), '-'); + let signature = FormDataHandler.boundaryHash(strippedBody); return signature; } FormDataHandler.boundaryHash = function (string) { - var shasum = crypto.createHash('sha1'); + let shasum = crypto.createHash('sha1'); shasum.update(string); return 'mockingjays' + shasum.digest('hex'); }; FormDataHandler.setHeaderBoundary = function (oldBoundary, newBoundary, newRequest) { - var {headers, body} = newRequest; + let {headers, body} = newRequest; headers[CONTENT_TYPE] = headers[CONTENT_TYPE].replace(new RegExp(oldBoundary, 'g'), newBoundary); headers[CONTENT_LENGTH] = body.length; @@ -52,15 +52,15 @@ FormDataHandler.setBodyBoundary = function (oldBoundary, newBoundary, body) { FormDataHandler.updateBoundary = function (request) { - var newRequest = Util.simpleCopy(request); + let newRequest = Util.simpleCopy(request); if (!FormDataHandler.isFormData(request.headers)) { return newRequest; } - var headers = newRequest.headers; - var body = newRequest.body; - var oldBoundary = FormDataHandler.getBoundary(headers[CONTENT_TYPE]); - var newBoundary = FormDataHandler.getBodySignature(oldBoundary, body); + let headers = newRequest.headers; + let body = newRequest.body; + let oldBoundary = FormDataHandler.getBoundary(headers[CONTENT_TYPE]); + let newBoundary = FormDataHandler.getBodySignature(oldBoundary, body); newRequest.body = FormDataHandler.setBodyBoundary(oldBoundary, newBoundary, body); newRequest.headers = FormDataHandler.setHeaderBoundary(oldBoundary, newBoundary, newRequest); diff --git a/src/header_util.js b/src/header_util.js index 3b0ce8a..b0ed63d 100644 --- a/src/header_util.js +++ b/src/header_util.js @@ -1,4 +1,4 @@ -var HEADER_WHITE_LIST = [ +let HEADER_WHITE_LIST = [ 'accept', 'authorization', 'content-length', @@ -9,8 +9,8 @@ var HEADER_WHITE_LIST = [ 'access-control-request-headers' ]; -var isInWhiteList = function(key, headers) { - var inWhiteList = HEADER_WHITE_LIST.indexOf(key) !== -1; +let isInWhiteList = function(key, headers) { + let inWhiteList = HEADER_WHITE_LIST.indexOf(key) !== -1; if (inWhiteList) { // Only include content length of non-zero length. return !(key === 'content-length' && headers[key] === "0"); @@ -19,14 +19,14 @@ var isInWhiteList = function(key, headers) { }; -var KNOWN_TEXTUAL_CONTENT_TYPES = [ +let KNOWN_TEXTUAL_CONTENT_TYPES = [ 'application/json', 'text/plain', 'text/html' ]; // Helper Reduction Function that take the cu -var getTextualContentTypeReducer = function (contentType) { +let getTextualContentTypeReducer = function (contentType) { return function (isTextual, current) { // Treating a missing content type as a textual type. return isTextual || !contentType || (contentType.indexOf(current) > -1); @@ -34,7 +34,7 @@ var getTextualContentTypeReducer = function (contentType) { } -var HeaderUtil = { +let HeaderUtil = { HEADER_WHITE_LIST: HEADER_WHITE_LIST, KNOWN_TEXTUAL_CONTENT_TYPES: KNOWN_TEXTUAL_CONTENT_TYPES }; @@ -57,10 +57,10 @@ HeaderUtil.isText = function (contentType) { * requestHeaders - Object of headers to filter. */ HeaderUtil.filterHeaders = function (wantedHeaders, requestHeaders) { - var headers = {}; - var key; + let headers = {}; + let key; wantedHeaders = wantedHeaders || []; - for (var index = 0; index < wantedHeaders.length; index++) { + for (let index = 0; index < wantedHeaders.length; index++) { key = wantedHeaders[index]; if (requestHeaders[key]) { headers[key] = requestHeaders[key]; @@ -77,9 +77,9 @@ HeaderUtil.filterHeaders = function (wantedHeaders, requestHeaders) { * requestHeaders - Object of headers. */ HeaderUtil.removeHeaders = function (targetHeader, requestHeaders) { - var headers = {}; + let headers = {}; targetHeader = targetHeader || []; - for (var key in requestHeaders) { + for (let key in requestHeaders) { if (targetHeader.indexOf(key.toLowerCase()) == -1) { headers[key] = requestHeaders[key]; } @@ -112,9 +112,9 @@ HeaderUtil.getCorsHeaders = function (origin) { * Variability in headers leads to a different hash for and file signatures. */ HeaderUtil.standardize = function (requestHeaders) { - var headers = HeaderUtil.sortHeaders(requestHeaders); - var allowedHeaders = {}; - for (var key in headers) { + let headers = HeaderUtil.sortHeaders(requestHeaders); + let allowedHeaders = {}; + for (let key in headers) { if (isInWhiteList(key, headers)) { allowedHeaders[key] = headers[key]; } @@ -131,14 +131,14 @@ HeaderUtil.standardize = function (requestHeaders) { */ HeaderUtil.sortHeaders = function (requestHeaders) { // Sort the keys to get predictable order in object keys. - var keys = []; - for (var key in requestHeaders) { + let keys = []; + for (let key in requestHeaders) { keys.push(key); } keys.sort(); // Copy the Keys in order: - var headers = {}; + let headers = {}; keys.forEach(function(key) { // Standardize the key to be lowercase: headers[key.toLowerCase()] = requestHeaders[key]; diff --git a/src/http_client.js b/src/http_client.js index 91e2505..bc06e34 100644 --- a/src/http_client.js +++ b/src/http_client.js @@ -5,7 +5,7 @@ import https from 'https' import HeaderUtil from './header_util'; import Util from './util'; -var HttpClient = function (options) { +let HttpClient = function (options) { this.options = options; this.logger = options.logger; } @@ -15,12 +15,12 @@ HttpClient.prototype.isIgnoredType = function(contentType) { } HttpClient.prototype.fetch = function (requestOptions, outputBuffer) { - var self = this; - var protocolHandler = requestOptions.port == 443 ? https : http; + let self = this; + let protocolHandler = requestOptions.port == 443 ? https : http; return new Promise(function(resolve, reject) { - var req = protocolHandler.request(requestOptions, function(res) { - var statusCode = res.statusCode; + let req = protocolHandler.request(requestOptions, function(res) { + let statusCode = res.statusCode; if (HeaderUtil.isText(res.headers['content-type'])) { self._accumulateResponse(res, requestOptions, resolve, reject); } else { @@ -41,7 +41,7 @@ HttpClient.prototype.fetch = function (requestOptions, outputBuffer) { req.end() req.on('error', function (error) { - var isIgnoredContentType = self.isIgnoredType(requestOptions.headers.accept) + let isIgnoredContentType = self.isIgnoredType(requestOptions.headers.accept) switch (error.code) { case 'ENOTFOUND': if (!isIgnoredContentType) { @@ -62,8 +62,8 @@ HttpClient.prototype.fetch = function (requestOptions, outputBuffer) { HttpClient.prototype._pipeResonse = function (res, outputBuffer, resolve, reject) { - var contentType = res.headers['content-type']; - var statusCode = res.statusCode + let contentType = res.headers['content-type']; + let statusCode = res.statusCode res.pipe(outputBuffer); resolve({ @@ -76,15 +76,15 @@ HttpClient.prototype._pipeResonse = function (res, outputBuffer, resolve, reject HttpClient.prototype._accumulateResponse = function (res, options, resolve, reject) { - var contentType = res.headers['content-type']; - var statusCode = res.statusCode; - var responseData = ''; + let contentType = res.headers['content-type']; + let statusCode = res.statusCode; + let responseData = ''; res.on('data', function (chunk) { responseData += chunk; }); res.on('end', function() { - var isJson = contentType === 'application/json'; + let isJson = contentType === 'application/json'; resolve({ request: options, status: statusCode, diff --git a/src/logger.js b/src/logger.js index f357360..f6018f0 100644 --- a/src/logger.js +++ b/src/logger.js @@ -1,13 +1,13 @@ import Colorize from './colorize'; -var Level = { +let Level = { ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 }; -var Logger = function() { +let Logger = function() { this.level = Level.INFO; if (arguments.length > 0) { this.setLevel.apply(this, arguments); @@ -61,8 +61,8 @@ Logger.prototype.warn = function () { Logger.prototype.log = function () { - var level = arguments[0]; - var messages = Array.prototype.slice.call(arguments, 1); + let level = arguments[0]; + let messages = Array.prototype.slice.call(arguments, 1); if (messages.length == 1 && messages[0] === 'false') { return; } @@ -85,12 +85,12 @@ Logger.prototype.log = function () { } Logger.prototype.formatLines = function (lines) { - var newLines = []; - for (var index = 0; index < lines.length; index++) { - var multiline = lines[index].toString().split('\n'); - for (var subindex = 0; subindex < multiline.length; subindex++) { - var prefix = subindex == 0 ? '' : ' '; - var suffix = multiline.length > 1 ? '\n' : ''; + let newLines = []; + for (let index = 0; index < lines.length; index++) { + let multiline = lines[index].toString().split('\n'); + for (let subindex = 0; subindex < multiline.length; subindex++) { + let prefix = subindex == 0 ? '' : ' '; + let suffix = multiline.length > 1 ? '\n' : ''; newLines.push(prefix + multiline[subindex] + suffix); } } diff --git a/src/mockingjay.js b/src/mockingjay.js index fb9bcfc..d4c5334 100644 --- a/src/mockingjay.js +++ b/src/mockingjay.js @@ -14,9 +14,9 @@ import Logger from './logger'; import TransactionState from './transaction_state'; import Util from './util'; -var logger = new Logger(); +let logger = new Logger(); -var Mockingjay = function(options) { +let Mockingjay = function(options) { this.options = options; this.options.logger = logger; logger.setLevel(options.logLevel); @@ -50,8 +50,8 @@ Mockingjay.prototype.learnOrPipe = function(request, outputBuffer) { } logger.info(Colorize.red('Learning'), JSON.stringify(request)); - var self = this; - var responsePromise = this.httpClient.fetch(request, outputBuffer); + let self = this; + let responsePromise = this.httpClient.fetch(request, outputBuffer); return responsePromise.then(function (response) { if (request.method == 'OPTIONS' || self._okToCache(response.headers['content-type'])) { return self.cacheClient.record(request, response); @@ -76,16 +76,16 @@ Mockingjay.prototype._okToCache = function (responseType) { * or need to fetch a fresh response. */ Mockingjay.prototype.echo = function(request, outputBuffer) { - var self = this; - var shouldRepeat = this.knows(request) && !this.options.refresh; - var responsePromise = shouldRepeat ? this.repeat(request) : this.learnOrPipe(request, outputBuffer); + let self = this; + let shouldRepeat = this.knows(request) && !this.options.refresh; + let responsePromise = shouldRepeat ? this.repeat(request) : this.learnOrPipe(request, outputBuffer); self.recordToRequestResponseLog('Hash', this.cacheClient.requestHash(request)); self.recordToRequestResponseLog('Request', Util.stringify(request)); responsePromise.then(function(response) { logger.info('Responding:', response.status, response.type); self.recordToRequestResponseLog('Response', Util.stringify(response), {end: true}); if (!response.piped) { - var responseString = typeof(response.data) === 'string' ? response.data : Util.stringify(response.data); + let responseString = typeof(response.data) === 'string' ? response.data : Util.stringify(response.data); if (HeaderUtil.isText(response.type)) { logger.info(responseString); } @@ -115,7 +115,7 @@ Mockingjay.prototype.recordToRequestResponseLog = function(key, value, additiona if (!this.options.requestResponseLogFile) { return; } - var line = key + ': ' + value + '\n' + (additionalOptions.end ? '\n' : ''); + let line = key + ': ' + value + '\n' + (additionalOptions.end ? '\n' : ''); fs.appendFile(this.options.requestResponseLogFile, line, (err) => { if (err) throw err; }); @@ -127,10 +127,10 @@ Mockingjay.prototype.recordToRequestResponseLog = function(key, value, additiona */ Mockingjay.prototype.onRequest = function(request, response) { logger.info(Colorize.green('Request Received'), request.url, request.method); - var simplifiedRequest = this.simplify(request); - var corsHeaders = HeaderUtil.getCorsHeaders(request.headers.origin); + let simplifiedRequest = this.simplify(request); + let corsHeaders = HeaderUtil.getCorsHeaders(request.headers.origin); - for (var corsHeader in corsHeaders) { + for (let corsHeader in corsHeaders) { response.setHeader(corsHeader, corsHeaders[corsHeader]); } @@ -152,9 +152,9 @@ Mockingjay.prototype.onRequest = function(request, response) { Mockingjay.prototype.simplify = function (request) { - var urlSplit = url.parse(this.options.serverBaseUrl + request.url); - var isHttps = urlSplit.protocol === 'https:' - var options = { + let urlSplit = url.parse(this.options.serverBaseUrl + request.url); + let isHttps = urlSplit.protocol === 'https:' + let options = { hostname: urlSplit.hostname, port: parseInt(urlSplit.port) || (isHttps ? 443 : 80), path: urlSplit.path, diff --git a/src/rehasher.js b/src/rehasher.js index 8e0555d..83cbee2 100644 --- a/src/rehasher.js +++ b/src/rehasher.js @@ -7,7 +7,7 @@ import HeaderUtil from './header_util'; import Logger from './logger'; import Util from './util'; -var Rehashser = function (options) { +let Rehashser = function (options) { this.logger = new Logger(); this.options = options; @@ -22,7 +22,7 @@ var Rehashser = function (options) { } Rehashser.prototype.process = function () { - var self = this; + let self = this; FileSystemHelper .findDirectories(this.options.cacheDir) .forEach(this.rehashWithOptions(this.options)) @@ -30,15 +30,15 @@ Rehashser.prototype.process = function () { Rehashser.prototype.rehashWithOptions = function(options) { - var self = this; + let self = this; return function (root) { - var notADirectory = function(file) {return !FileSystemHelper.directoryExists(file)}; + let notADirectory = function(file) {return !FileSystemHelper.directoryExists(file)}; FileSystemHelper .findFileType(root, notADirectory) .forEach(function (file) { self.getContents(file) .then(function(cachedContents) { - var originalCachedContents = Util.parseJSON(Util.stringify(cachedContents)); + let originalCachedContents = Util.parseJSON(Util.stringify(cachedContents)); self.updateResponseWithOptions(cachedContents); self.updateRequestWithOptions(cachedContents); self.updateFile(file, cachedContents, originalCachedContents); @@ -53,7 +53,7 @@ Rehashser.prototype.getContents = function(file) { if (err) { reject(err); } else { - var cachedData = Util.parseJSON(data); + let cachedData = Util.parseJSON(data); resolve(cachedData); } }); @@ -61,13 +61,13 @@ Rehashser.prototype.getContents = function(file) { } Rehashser.prototype.updateResponseWithOptions = function(cacheContent) { - var reducedHeaders = HeaderUtil.removeHeaders(this.options.responseHeaderBlacklist, cacheContent.headers); + let reducedHeaders = HeaderUtil.removeHeaders(this.options.responseHeaderBlacklist, cacheContent.headers); cacheContent.headers = reducedHeaders; } Rehashser.prototype.updateRequestWithOptions = function(cacheContent) { - var filteredHeaders = HeaderUtil.filterHeaders(this.options.cacheHeaders, cacheContent.request.headers); - var urlInfo = Url.parse(this.options.serverBaseUrl); // Update Base Server URL + let filteredHeaders = HeaderUtil.filterHeaders(this.options.cacheHeaders, cacheContent.request.headers); + let urlInfo = Url.parse(this.options.serverBaseUrl); // Update Base Server URL cacheContent.request.hostname = urlInfo.hostname; cacheContent.request.headers = filteredHeaders; @@ -76,7 +76,7 @@ Rehashser.prototype.updateRequestWithOptions = function(cacheContent) { } Rehashser.prototype.updateFile = function(filePath, cacheContent, originalCachedContents) { - var cacheClient = this.cacheClient; + let cacheClient = this.cacheClient; if (cacheClient.isCached(cacheContent.request)) { this.logger.info('Updating Contents for for File:', filePath); cacheClient.record(cacheContent.request, cacheContent); diff --git a/src/request_hash.js b/src/request_hash.js index ae48843..1bef2cb 100644 --- a/src/request_hash.js +++ b/src/request_hash.js @@ -3,7 +3,7 @@ import crypto from 'crypto'; import Util from './util'; import HeaderUtil from './header_util'; -var RequestHash = function (request, cacheHeaders, whiteLabel, ignoreJsonBodyPath) { +let RequestHash = function (request, cacheHeaders, whiteLabel, ignoreJsonBodyPath) { this.request = request; this.cacheHeaders = cacheHeaders; this.whiteLabel = whiteLabel; @@ -12,19 +12,19 @@ var RequestHash = function (request, cacheHeaders, whiteLabel, ignoreJsonBodyPat RequestHash.prototype.toString = function () { - var request = this._filteredAttributes(); + let request = this._filteredAttributes(); if (request.body) { // Backward Compatability Hash with Existing Fixture Files request.body = JSON.stringify(request.body); } - var shasum = crypto.createHash('sha1'); + let shasum = crypto.createHash('sha1'); shasum.update(JSON.stringify(Util.sortObjectKeys(request))); return shasum.digest('hex'); }; RequestHash.prototype._filteredAttributes = function () { - var filteredAttributes = Util.simpleCopy(this.request); + let filteredAttributes = Util.simpleCopy(this.request); filteredAttributes.headers = HeaderUtil.filterHeaders(this.cacheHeaders, this.request.headers); if (this.whiteLabel) { filteredAttributes.hostname = 'example.com'; diff --git a/src/server.js b/src/server.js index 9259afd..3048d1f 100644 --- a/src/server.js +++ b/src/server.js @@ -2,7 +2,7 @@ import http from 'http'; import httpShutdown from 'http-shutdown'; function listen (options, requestHandler, onReady) { - var server = httpShutdown(http.createServer(requestHandler)); + let server = httpShutdown(http.createServer(requestHandler)); server.listen(options.port, (onReady || function() {})); return server; }; diff --git a/src/transaction_state.js b/src/transaction_state.js index cbeed61..f75a246 100644 --- a/src/transaction_state.js +++ b/src/transaction_state.js @@ -1,4 +1,4 @@ -var TransactionState = function (transactionOptions) { +let TransactionState = function (transactionOptions) { this.options = transactionOptions; this.transactionMap = {}; } @@ -12,17 +12,17 @@ TransactionState.prototype.get = function (path, method) { } TransactionState.prototype.isStateful = function(path, method) { - var isDefined = Boolean(this.options[path]); - var methodsMatch = isDefined && Boolean(this.options[path].method === method); + let isDefined = Boolean(this.options[path]); + let methodsMatch = isDefined && Boolean(this.options[path].method === method); return isDefined && methodsMatch; } TransactionState.prototype.set = function (statefulPath, method, transactionKey) { - var self = this; + let self = this; if(!this.options[statefulPath]) { return; } else { - var affectedPaths = this.options[statefulPath].links; + let affectedPaths = this.options[statefulPath].links; affectedPaths.forEach(function (pathOptions) { self.transactionMap[pathOptions.path + pathOptions.method] = transactionKey; }); diff --git a/src/util.js b/src/util.js index 0398f23..4bc7fb8 100644 --- a/src/util.js +++ b/src/util.js @@ -1,17 +1,17 @@ import Logger from './logger'; -var Util = { +let Util = { logger: new Logger() }; Util.determinePort = function (urlInfo) { - var isHttps = urlInfo.protocol === 'https:' + let isHttps = urlInfo.protocol === 'https:' return parseInt(urlInfo.port) || (isHttps ? 443 : 80); } Util.stringify = function (inputObject) { - var jsonObject = inputObject || ''; + let jsonObject = inputObject || ''; try { switch (typeof(jsonObject)) { @@ -46,8 +46,8 @@ Util.simpleCopy = function (target) { Util.regExArrayContains = function (regExArray, value) { - var inList = function (expressionMatched, next) { - var matchList = new RegExp(next).exec(value); + let inList = function (expressionMatched, next) { + let matchList = new RegExp(next).exec(value); return expressionMatched || Boolean(matchList && matchList.length > 0); }; return regExArray.reduce(inList, false); @@ -56,14 +56,14 @@ Util.regExArrayContains = function (regExArray, value) { Util.sortObjectKeys = function (originalObject) { // Sort the keys to get predictable order in object keys. - var keys = []; - for (var key in originalObject) { + let keys = []; + for (let key in originalObject) { keys.push(key); } keys.sort(); // Copy the Keys in order: - var resultObject = {}; + let resultObject = {}; keys.forEach(function(key) { // Standardize the key to be lowercase: resultObject[key.toLowerCase()] = originalObject[key]; diff --git a/test/cache_client_spec.js b/test/cache_client_spec.js index 284d81e..2eac890 100644 --- a/test/cache_client_spec.js +++ b/test/cache_client_spec.js @@ -5,7 +5,7 @@ import CacheClient from '../src/cache_client'; describe('CacheClient', () => { context('simple options', () => { beforeEach(function() { - var userOptions = { + let userOptions = { cacheDir: '/Users/home/fixtures', cacheHeader: ['authorization'] }; @@ -117,7 +117,7 @@ describe('CacheClient', () => { }) it('should return the different hash for identical requests with different headers', function() { - var copyRequest = { + let copyRequest = { hostname: 'swapi.co', path: '/api/', port: 80, @@ -129,7 +129,7 @@ describe('CacheClient', () => { expect(this.client.requestHash(this.requests[0])).to.not.equal(this.client.requestHash(copyRequest)) // Differet Client Different Options not considering any headers - var newClient = new CacheClient({cacheDir: '/Users/home/fixtures'}); + let newClient = new CacheClient({cacheDir: '/Users/home/fixtures'}); expect(newClient.requestHash(this.requests[0])).to.equal(newClient.requestHash(copyRequest)) }); diff --git a/test/default_options_spec.js b/test/default_options_spec.js index dbfbc0e..8bcf7ac 100644 --- a/test/default_options_spec.js +++ b/test/default_options_spec.js @@ -5,8 +5,8 @@ import DefaultOptions from '../src/default_options'; describe('DefaultOptions', function() { describe('_handeBaseUrlDefault', function() { - var defaults = new DefaultOptions(); // Deafaults Object is not stateful. - var userProvidedInput = {} + let defaults = new DefaultOptions(); // Deafaults Object is not stateful. + let userProvidedInput = {} it('should expect a serverBaseUrl value from the user', function() { expect(function() { defaults._handleBaseUrlDefault(userProvidedInput)}).to.throw('serverBaseUrl is required! It can not be empty.'); @@ -15,8 +15,8 @@ describe('DefaultOptions', function() { describe('_handleCacheDirectoryDefault', function() { - var defaults = new DefaultOptions(); // Deafaults Object is not stateful. - var userProvidedInput = {} + let defaults = new DefaultOptions(); // Deafaults Object is not stateful. + let userProvidedInput = {} it('should expect a default cacheDir value from the user', function() { expect(function() { defaults._handleCacheDirectoryDefault(userProvidedInput)}).to.throw('cacheDir is required! It can not be empty.'); @@ -25,10 +25,10 @@ describe('DefaultOptions', function() { describe('merge()', function() { - var defaults = new DefaultOptions(); // Deafaults Object is not stateful. + let defaults = new DefaultOptions(); // Deafaults Object is not stateful. it('merges successuflly when ALL options are provided', function () { - var userProvidedOptions = { + let userProvidedOptions = { overrideCacheDir: '/var/base/fixtures', cacheDir: '/var/app/fixtures', serverBaseUrl: 'http://swapi.co', @@ -43,7 +43,7 @@ describe('DefaultOptions', function() { whiteLabel: true }; - var expectedOptionsOutput = { + let expectedOptionsOutput = { accessLogFile: null, overrideCacheDir: '/var/base/fixtures', cacheDir: '/var/app/fixtures', @@ -68,12 +68,12 @@ describe('DefaultOptions', function() { it('merges successuflly when MINIMUM options are provided', function () { - var userProvidedOptions = { + let userProvidedOptions = { cacheDir: '/var/app/fixtures', serverBaseUrl: 'http://swapi.co', }; - var expectedOptionsOutput = { + let expectedOptionsOutput = { // Provided Values overrideCacheDir: null, cacheDir: '/var/app/fixtures', diff --git a/test/form_data_spec.js b/test/form_data_spec.js index e803b9e..48449ca 100644 --- a/test/form_data_spec.js +++ b/test/form_data_spec.js @@ -5,14 +5,14 @@ describe('Form Data Handler', function () { describe('isFormData', function () { it('should return true for form content-type', function () { - var actualResult = FormDataHandler.isFormData({ + let actualResult = FormDataHandler.isFormData({ 'content-type': 'multipart/form-data' }); expect(actualResult).to.be.ok }); it('should return false for non-form content types', function () { - var actualResult = FormDataHandler.isFormData({ + let actualResult = FormDataHandler.isFormData({ 'content-type': 'application/json' }); @@ -23,14 +23,14 @@ describe('Form Data Handler', function () { describe('updateBoundary', function () { it('should update the boundary for a form content-type', function () { - var request = { + let request = { headers:{ 'content-type': "multipart/form-data; boundary=\"test123\"" }, body: "--test123\r\nContent-Disposition: form-data; name=\"file\"; filename=\"valid-file.csv\"\r\nContent-Type: application/octet-stream\r\n\r\nsample-data\r\n--test123--\r\n" } - var newRequest = FormDataHandler.updateBoundary(request); + let newRequest = FormDataHandler.updateBoundary(request); expect(newRequest).to.deep.equal({ headers: { @@ -43,14 +43,14 @@ describe('Form Data Handler', function () { it('should update the boundary for a form content-type without quotes', function () { - var request = { + let request = { headers:{ 'content-type': "multipart/form-data; boundary=quoteless123" }, body: "--quoteless123\r\nContent-Disposition: form-data; name=\"file\"; filename=\"valid-file.csv\"\r\nContent-Type: application/octet-stream\r\n\r\nsample-data\r\n--quoteless123--\r\n" } - var newRequest = FormDataHandler.updateBoundary(request); + let newRequest = FormDataHandler.updateBoundary(request); expect(newRequest).to.deep.equal({ headers: { @@ -63,7 +63,7 @@ describe('Form Data Handler', function () { it('should not update the boundary for a form content-type', function () { - var request = { + let request = { headers:{ 'content-type': "application/json" }, @@ -72,7 +72,7 @@ describe('Form Data Handler', function () { } } - var newRequest = FormDataHandler.updateBoundary(request); + let newRequest = FormDataHandler.updateBoundary(request); expect(newRequest).to.deep.equal(request); }); diff --git a/test/header_util_spec.js b/test/header_util_spec.js index b94a1d3..8f09bd8 100644 --- a/test/header_util_spec.js +++ b/test/header_util_spec.js @@ -6,14 +6,14 @@ describe('Header Util', function () { describe('isText', function () { it('should return true for textual content types', function () { - var trueExamples = HeaderUtil.KNOWN_TEXTUAL_CONTENT_TYPES; + let trueExamples = HeaderUtil.KNOWN_TEXTUAL_CONTENT_TYPES; trueExamples.forEach(function (example) { expect(HeaderUtil.isText(example)).to.be.true; }); }); it('should return false for unknown content types', function () { - var trueExamples = [ + let trueExamples = [ 'image/png', 'image/jpg', 'application/pdf' @@ -27,15 +27,15 @@ describe('Header Util', function () { describe('filterHeaders', function () { - var exampleHeaders = { + let exampleHeaders = { 'content-type': 'application/json', 'authorization': 'Basic 123456', 'content-length': '123' } it('should remove filters NOT in the wanted list', function() { - var headersToKeep = ['content-type', 'authorization']; - var actual = HeaderUtil.filterHeaders(headersToKeep, exampleHeaders); + let headersToKeep = ['content-type', 'authorization']; + let actual = HeaderUtil.filterHeaders(headersToKeep, exampleHeaders); expect(actual).to.deep.equal({ 'content-type': 'application/json', @@ -45,8 +45,8 @@ describe('Header Util', function () { it('should remove filters NOT in the wanted list', function() { - var headersToKeep = ['content-type']; - var actual = HeaderUtil.filterHeaders(headersToKeep, exampleHeaders); + let headersToKeep = ['content-type']; + let actual = HeaderUtil.filterHeaders(headersToKeep, exampleHeaders); expect(actual).to.deep.equal({ 'content-type': 'application/json' }); @@ -61,15 +61,15 @@ describe('Header Util', function () { describe('removeHeaders', function () { - var exampleHeaders = { + let exampleHeaders = { 'content-type': 'application/json', 'authorization': 'Basic 123456', 'content-length': '123' } it('should remove headers in the remove list', function() { - var headersToRemove = ['content-type', 'authorization']; - var actual = HeaderUtil.removeHeaders(headersToRemove, exampleHeaders); + let headersToRemove = ['content-type', 'authorization']; + let actual = HeaderUtil.removeHeaders(headersToRemove, exampleHeaders); expect(actual).to.deep.equal({ 'content-length': '123' }); @@ -77,8 +77,8 @@ describe('Header Util', function () { it('should remove header in the wanted list', function() { - var headersToRemove = ['content-type']; - var actual = HeaderUtil.removeHeaders(headersToRemove, exampleHeaders); + let headersToRemove = ['content-type']; + let actual = HeaderUtil.removeHeaders(headersToRemove, exampleHeaders); expect(actual).to.deep.equal({ 'content-length': '123', 'authorization': 'Basic 123456' @@ -94,15 +94,15 @@ describe('Header Util', function () { describe('sortHeaders', function () { it('should remove filters NOT in the wanted list', function() { - var actual = HeaderUtil.sortHeaders({ + let actual = HeaderUtil.sortHeaders({ 'zyx': '789', 'def': '456', 'ghi': '753', 'abc': '123' }); - var expectedOrder = ['abc', 'def', 'ghi', 'zyx'] - var index = 0; - for (var key in actual) { + let expectedOrder = ['abc', 'def', 'ghi', 'zyx'] + let index = 0; + for (let key in actual) { expect(key).to.deep.equal(expectedOrder[index]); index++; } @@ -112,12 +112,12 @@ describe('Header Util', function () { describe('standardize', function () { it('should remove headers not part of the whitelist', function() { - var actual = HeaderUtil.standardize({'zyx': '789', 'def': '456',}); + let actual = HeaderUtil.standardize({'zyx': '789', 'def': '456',}); expect(actual).to.deep.equal({}); }); it('should keep headers part of the whitelist', function() { - var exampleHeaders = { + let exampleHeaders = { 'authorization': 'Basic 12345', 'content-length': '123', 'content-type': 'application/json', @@ -126,25 +126,25 @@ describe('Header Util', function () { 'access-control-request-headers': '*' } - var actual = HeaderUtil.standardize(exampleHeaders); + let actual = HeaderUtil.standardize(exampleHeaders); expect(actual).to.deep.equal(exampleHeaders); }); it('should remove content-legth when it is zero', function() { - var exampleHeaders = {'content-length': '0', 'authorization': 'Basic 12345'}; - var actual = HeaderUtil.standardize(exampleHeaders); + let exampleHeaders = {'content-length': '0', 'authorization': 'Basic 12345'}; + let actual = HeaderUtil.standardize(exampleHeaders); expect(actual).to.deep.equal({'authorization': 'Basic 12345'}); }); it('should remove headers NOT in whitelist', function() { - var exampleHeaders = { + let exampleHeaders = { 'authorization': 'Basic 12345', 'cookie': 'abc=123;', 'date': 'Today', 'pragma': 'pragma-value' }; - var actual = HeaderUtil.standardize(exampleHeaders); + let actual = HeaderUtil.standardize(exampleHeaders); expect(actual).to.deep.equal({'authorization': 'Basic 12345'}); }); }); @@ -152,7 +152,7 @@ describe('Header Util', function () { describe('getCorsHeaders', function () { it('should return an object of headers', function() { - var actual = HeaderUtil.getCorsHeaders(); + let actual = HeaderUtil.getCorsHeaders(); expect(actual).to.be.ok; expect(actual).to.deep.equal({ "Access-Control-Allow-Credentials": "true", @@ -165,8 +165,8 @@ describe('Header Util', function () { it('should return an object with the origin of the request', function() { - var origin = 'http://example.com' - var actual = HeaderUtil.getCorsHeaders(origin); + let origin = 'http://example.com' + let actual = HeaderUtil.getCorsHeaders(origin); expect(actual).to.be.ok; expect(actual).to.deep.equal({ "Access-Control-Allow-Credentials": "true", diff --git a/test/http_client_spec.js b/test/http_client_spec.js index 4b5cf73..41b2066 100644 --- a/test/http_client_spec.js +++ b/test/http_client_spec.js @@ -13,7 +13,7 @@ describe('HttpClient', function () { describe('isIgnoredType', function() { it('should not log for ignored content-types', function() { - var contentType = 'image/*;text/html;' + let contentType = 'image/*;text/html;' expect(this.http_client.isIgnoredType(contentType)).to.be.ok }); }); diff --git a/test/mockingjay_spec.js b/test/mockingjay_spec.js index d41a568..f5aa495 100644 --- a/test/mockingjay_spec.js +++ b/test/mockingjay_spec.js @@ -4,10 +4,10 @@ import Mockingjay from '../src/mockingjay'; describe('Mockingjay', function () { describe('simplify', function () { - var mockingjay = new Mockingjay({serverBaseUrl: 'http://www.google.com'}); + let mockingjay = new Mockingjay({serverBaseUrl: 'http://www.google.com'}); it('should prepare options for HTTP request', function () { - var givenRequest = { + let givenRequest = { url: '/query', method: 'GET', body: '', diff --git a/test/option_parser_spec.js b/test/option_parser_spec.js index f410beb..4054e77 100644 --- a/test/option_parser_spec.js +++ b/test/option_parser_spec.js @@ -6,7 +6,7 @@ describe('Option Parser', function() { describe('parse', function () { it('should return the string value of a failed parse attempt', function () { - var exmapleArguments = [ + let exmapleArguments = [ 'node', 'mockingjays', 'serve', @@ -14,7 +14,7 @@ describe('Option Parser', function() { '--cacheDir=/var/temp/fixtures' ] - var expectedOptions = { + let expectedOptions = { command: 'serve', baseServerUrl: 'http://google.com', cacheDir: '/var/temp/fixtures' diff --git a/test/request_hash_spec.js b/test/request_hash_spec.js index bd353e6..cf2e9f9 100644 --- a/test/request_hash_spec.js +++ b/test/request_hash_spec.js @@ -3,7 +3,7 @@ import RequestHash from '../src/request_hash'; describe('RequestHash with Empty Body', function() { - var exampleRequestA = { + let exampleRequestA = { hostname: 'swapi.co', path: '/api/', port: 80, @@ -11,7 +11,7 @@ describe('RequestHash with Empty Body', function() { body: '' } - var exampleRequestADomainB = { + let exampleRequestADomainB = { hostname: 'notarealdomain.com', path: '/api/', port: 8080, @@ -19,7 +19,7 @@ describe('RequestHash with Empty Body', function() { body: '' } - var exampleRequestB = { + let exampleRequestB = { hostname: 'swapi.co', path: '/api/people/1/', port: 80, @@ -29,33 +29,33 @@ describe('RequestHash with Empty Body', function() { describe('toString()', function() { it('should NOT be equal when headers are considered', function () { - var cacheHeadersAuthorization = ['authorization'] - var hashA = new RequestHash(exampleRequestA, cacheHeadersAuthorization); - var hashB = new RequestHash(exampleRequestB, cacheHeadersAuthorization); + let cacheHeadersAuthorization = ['authorization'] + let hashA = new RequestHash(exampleRequestA, cacheHeadersAuthorization); + let hashB = new RequestHash(exampleRequestB, cacheHeadersAuthorization); expect(hashA.toString()).to.not.equal(hashB.toString()); }); it('should be NOT be equal when headers are not considered', function () { - var cacheHeaders = [] - var hashA = new RequestHash(exampleRequestA, cacheHeaders); - var hashB = new RequestHash(exampleRequestB, cacheHeaders); + let cacheHeaders = [] + let hashA = new RequestHash(exampleRequestA, cacheHeaders); + let hashB = new RequestHash(exampleRequestB, cacheHeaders); expect(hashA.toString()).to.not.equal(hashB.toString()); }); it('should hash to a different value with a white label flag', function () { - var cacheHeaders = [] - var hashAWhiteLabel = new RequestHash(exampleRequestA, cacheHeaders, true); - var hashA = new RequestHash(exampleRequestA, cacheHeaders); + let cacheHeaders = [] + let hashAWhiteLabel = new RequestHash(exampleRequestA, cacheHeaders, true); + let hashA = new RequestHash(exampleRequestA, cacheHeaders); expect(hashAWhiteLabel.toString()).to.not.equal(hashA.toString()); }); it('should hash to the same value with a white label flag', function () { - var cacheHeaders = [] - var hashA = new RequestHash(exampleRequestA, cacheHeaders, true); - var hashB = new RequestHash(exampleRequestADomainB, cacheHeaders, true); + let cacheHeaders = [] + let hashA = new RequestHash(exampleRequestA, cacheHeaders, true); + let hashB = new RequestHash(exampleRequestADomainB, cacheHeaders, true); expect(hashA.toString()).to.equal(hashB.toString()); }); }); @@ -63,24 +63,24 @@ describe('RequestHash with Empty Body', function() { describe('_filteredAttributes()', function() { it('should NOT be equal when headers are included', function () { - var cacheHeadersAuthorization = ['authorization'] - var hashA = new RequestHash(exampleRequestA, cacheHeadersAuthorization); - var hashB = new RequestHash(exampleRequestB, cacheHeadersAuthorization); + let cacheHeadersAuthorization = ['authorization'] + let hashA = new RequestHash(exampleRequestA, cacheHeadersAuthorization); + let hashB = new RequestHash(exampleRequestB, cacheHeadersAuthorization); expect(hashA._filteredAttributes()).to.not.deep.equal(hashB._filteredAttributes()); }); it('should be NOT be equal when headers are excluded', function () { - var cacheHeaders = [] - var hashA = new RequestHash(exampleRequestA, cacheHeaders); - var hashB = new RequestHash(exampleRequestB, cacheHeaders); + let cacheHeaders = [] + let hashA = new RequestHash(exampleRequestA, cacheHeaders); + let hashB = new RequestHash(exampleRequestB, cacheHeaders); expect(hashA._filteredAttributes()).to.not.deep.equal(hashB._filteredAttributes()); }); it('should be filter all headers out', function () { - var cacheHeaders = [] - var hashA = new RequestHash(exampleRequestA, cacheHeaders); + let cacheHeaders = [] + let hashA = new RequestHash(exampleRequestA, cacheHeaders); expect(hashA._filteredAttributes()).to.deep.equal({ hostname: 'swapi.co', path: '/api/', @@ -91,8 +91,8 @@ describe('RequestHash with Empty Body', function() { }); it('should be keep defined headers headers', function () { - var cacheHeaders = ['content-type'] - var hashA = new RequestHash(exampleRequestA, cacheHeaders); + let cacheHeaders = ['content-type'] + let hashA = new RequestHash(exampleRequestA, cacheHeaders); expect(hashA._filteredAttributes()).to.deep.equal({ hostname: 'swapi.co', path: '/api/', @@ -103,7 +103,7 @@ describe('RequestHash with Empty Body', function() { }); it('should be keep defined headers headers', function () { - var exampleRequestJSONBody = { + let exampleRequestJSONBody = { hostname: 'swapi.co', path: '/api/', port: 80, @@ -119,7 +119,7 @@ describe('RequestHash with Empty Body', function() { } }; - var hashA = new RequestHash(exampleRequestJSONBody, null, null, ['a.b.c']); + let hashA = new RequestHash(exampleRequestJSONBody, null, null, ['a.b.c']); expect(hashA._filteredAttributes()).to.deep.equal({ hostname: 'swapi.co', path: '/api/', @@ -139,7 +139,7 @@ describe('RequestHash with Empty Body', function() { it('should be not add a key if not already present', function () { - var exampleRequestJSONBody = { + let exampleRequestJSONBody = { hostname: 'swapi.co', path: '/api/', port: 80, @@ -151,7 +151,7 @@ describe('RequestHash with Empty Body', function() { } }; - var hashA = new RequestHash(exampleRequestJSONBody, null, null, ['a.b.c']); + let hashA = new RequestHash(exampleRequestJSONBody, null, null, ['a.b.c']); expect(hashA._filteredAttributes()).to.deep.equal({ hostname: 'swapi.co', path: '/api/', diff --git a/test/transaction_state_spec.js b/test/transaction_state_spec.js index d04bcb7..0f32a4f 100644 --- a/test/transaction_state_spec.js +++ b/test/transaction_state_spec.js @@ -5,7 +5,7 @@ import TransactionState from '../src/transaction_state'; describe('TransactionState', function() { describe('state with populated configuration', function() { - var transactionConfig = { + let transactionConfig = { "/api/": { "method": "GET", "status": 200, @@ -17,7 +17,7 @@ describe('TransactionState', function() { ] } } - var transactionState = new TransactionState(transactionConfig); + let transactionState = new TransactionState(transactionConfig); it('should identify stateful transaction', function () { expect(transactionState.isStateful('/api/', 'GET')).to.be.true; @@ -36,7 +36,7 @@ describe('TransactionState', function() { }); it('should return the key for a stateful transaction', function () { - var expectedKey = 'abcd1234beef'; + let expectedKey = 'abcd1234beef'; transactionState.set('/api/', 'GET', expectedKey); expect(transactionState.get('/api/people/1/', 'GET')).to.equal(expectedKey); @@ -50,7 +50,7 @@ describe('TransactionState', function() { describe('state with empty configuration', function() { - var transactionState = new TransactionState({}); + let transactionState = new TransactionState({}); it('should identify stateful transaction', function () { expect(transactionState.isStateful('/api/', 'GET')).to.be.false; @@ -66,7 +66,7 @@ describe('TransactionState', function() { }); it('should return the key for a stateful transaction', function () { - var expectedKey = 'abcd1234beef'; + let expectedKey = 'abcd1234beef'; transactionState.set('/api/', 'GET', expectedKey); // Should have no effect expect(transactionState.get('/api/people/1/', 'GET')).to.equal(''); expect(transactionState.get('/api/people/1/', 'POST')).to.equal(''); diff --git a/test/util_spec.js b/test/util_spec.js index e650dc9..3ea393d 100644 --- a/test/util_spec.js +++ b/test/util_spec.js @@ -22,7 +22,7 @@ describe('Util Functions', function() { describe('parseJSON', function () { it('should parse valid json', function () { - var exampleString = '{"example": "string value", "example2": 1, "example": [1, "abc"]}'; + let exampleString = '{"example": "string value", "example2": 1, "example": [1, "abc"]}'; expect(Util.parseJSON(exampleString)).to.deep.equal({ example: 'string value', example2: 1, @@ -31,7 +31,7 @@ describe('Util Functions', function() { }); it('should return the string value of a failed parse attempt', function () { - var exampleString = 'Exception occurred on server. Unable to process request.'; + let exampleString = 'Exception occurred on server. Unable to process request.'; expect(Util.parseJSON(exampleString)).to.deep.equal(exampleString); }); }); @@ -39,7 +39,7 @@ describe('Util Functions', function() { describe('stringify', function () { it('Stringify JSON', function () { - var exampleString = JSON.stringify(JSON.parse('{"example": "string value", "example2": 1, "example": [1, "abc"]}'), null, 2); + let exampleString = JSON.stringify(JSON.parse('{"example": "string value", "example2": 1, "example": [1, "abc"]}'), null, 2); expect(Util.stringify({ example: 'string value', @@ -49,22 +49,22 @@ describe('Util Functions', function() { }); it('should return the string if a string is provided', function () { - var exampleString = 'string-example'; + let exampleString = 'string-example'; expect(Util.stringify(exampleString)).to.equal(exampleString); }); it('should return the string if a number is provided', function () { - var exampleString = '123'; + let exampleString = '123'; expect(Util.stringify(123)).to.equal(exampleString); }); it('should call toString if a function is provided', function () { - var exampleFunction = function(){}; + let exampleFunction = function(){}; expect(Util.stringify(exampleFunction)).to.equal('[Function]'); }); it('should call toString if a circular reference exception is encountered', function () { - var circularObject = {}; + let circularObject = {}; circularObject.cycle = circularObject expect(Util.stringify(circularObject)).to.equal('[object Object]'); }); @@ -73,11 +73,11 @@ describe('Util Functions', function() { describe('simpleCopy', function () { it('should provide a copy of an object', function () { - var exampleObject = { + let exampleObject = { abc: 123, def: 456 }; - var copy = Util.simpleCopy(exampleObject); + let copy = Util.simpleCopy(exampleObject); expect(copy).to.deep.equal(exampleObject); // Equals copy.abc = 987; @@ -89,16 +89,16 @@ describe('Util Functions', function() { describe('regExArrayContains', function () { it('should match the value against a pattern', function () { - var regExList = ['image/.*', 'text/.*', 'application/json']; - var examples = ['image/png', 'image/jpg', 'text/plain', 'text/html', 'application/json']; + let regExList = ['image/.*', 'text/.*', 'application/json']; + let examples = ['image/png', 'image/jpg', 'text/plain', 'text/html', 'application/json']; examples.forEach(function (example) { expect(Util.regExArrayContains(regExList, example)).to.be.true }); }); it('should fail to match the value when pattern does not match', function () { - var regExList = ['image/.*', 'text/.*']; - var examples = ['application/json', 'application/image', 'plain/text']; + let regExList = ['image/.*', 'text/.*']; + let examples = ['application/json', 'application/image', 'plain/text']; examples.forEach(function (example) { expect(Util.regExArrayContains(regExList, example)).to.be.false });