From 71f7b5cc099250132725a573f7b5d401d313d77c Mon Sep 17 00:00:00 2001 From: Sebastian Malton Date: Thu, 31 Aug 2023 13:02:19 -0400 Subject: [PATCH] feat!: Remove async/await and make conversions sync - There were no requirements within the code to have them async Signed-off-by: Sebastian Malton --- src/converter.ts | 8 +- src/csv2json.ts | 17 +-- src/json2csv.ts | 98 ++++++------- test/csv2json.ts | 236 +++++++++++++++---------------- test/json2csv.ts | 356 ++++++++++++++++++++++++----------------------- 5 files changed, 360 insertions(+), 355 deletions(-) diff --git a/src/converter.ts b/src/converter.ts index aa0099d..2b41bd7 100644 --- a/src/converter.ts +++ b/src/converter.ts @@ -8,18 +8,18 @@ import { buildJ2COptions, buildC2JOptions, validate, isObject, isString } from ' export type { Json2CsvOptions, Csv2JsonOptions } from './types'; -export async function json2csv(data: object[], options?: Json2CsvOptions): Promise { +export function json2csv(data: object[], options?: Json2CsvOptions): string { const builtOptions = buildJ2COptions(options ?? {}); - + // Validate the parameters before calling the converter's convert function validate(data, isObject, errors.json2csv); return Json2Csv(builtOptions).convert(data); } -export async function csv2json(data: string, options?: Csv2JsonOptions): Promise { +export function csv2json(data: string, options?: Csv2JsonOptions): object[] { const builtOptions = buildC2JOptions(options ?? {}); - + // Validate the parameters before calling the converter's convert function validate(data, isString, errors.csv2json); diff --git a/src/csv2json.ts b/src/csv2json.ts index 7953763..2ca21a2 100644 --- a/src/csv2json.ts +++ b/src/csv2json.ts @@ -59,7 +59,7 @@ export const Csv2Json = function(options: FullCsv2JsonOptions) { /** * Removes the Excel BOM value, if specified by the options object */ - async function stripExcelBOM(csv: string) { + function stripExcelBOM(csv: string) { if (options.excelBOM) { return csv.replace(excelBOMRegex, ''); } @@ -80,7 +80,7 @@ export const Csv2Json = function(options: FullCsv2JsonOptions) { justParsedDoubleQuote: false, startIndex: 0 }; - + let splitLine = [], character, charBefore, @@ -363,13 +363,14 @@ export const Csv2Json = function(options: FullCsv2JsonOptions) { /** * Internally exported csv2json function */ - async function convert(data: string) { + function convert(data: string) { // Split the CSV into lines using the specified EOL option - return stripExcelBOM(data) - .then(splitLines) - .then(retrieveHeading) // Retrieve the headings from the CSV, unless the user specified the keys - .then(retrieveRecordLines) // Retrieve the record lines from the CSV - .then(transformRecordLines); // Retrieve the JSON document array + const stripped = stripExcelBOM(data); + const split = splitLines(stripped); + const heading = retrieveHeading(split); // Retrieve the headings from the CSV, unless the user specified the keys + const lines = retrieveRecordLines(heading); // Retrieve the record lines from the CSV + + return transformRecordLines(lines); // Retrieve the JSON document array } return { diff --git a/src/json2csv.ts b/src/json2csv.ts index 39ca479..96650be 100755 --- a/src/json2csv.ts +++ b/src/json2csv.ts @@ -23,7 +23,7 @@ export const Json2Csv = function(options: FullJson2CsvOptions) { /** * Returns the list of data field names of all documents in the provided list */ - async function getFieldNameList(data: object[]) { + function getFieldNameList(data: object[]) { // If keys weren't specified, then we'll use the list of keys generated by the deeks module return deepKeysFromList(data, deeksOptions); } @@ -161,21 +161,23 @@ export const Json2Csv = function(options: FullJson2CsvOptions) { */ function retrieveHeaderFields(data: object[]) { const keyStrings = convertKeysToHeaderFields(); - + if (options.keys) { options.keys = keyStrings; if (!options.unwindArrays) { - return Promise.resolve(keyStrings) - .then(filterExcludedKeys) - .then(sortHeaderFields); + const filtered = filterExcludedKeys(keyStrings); + + + return sortHeaderFields(filtered); } } - return getFieldNameList(data) - .then(processSchemas) - .then(filterExcludedKeys) - .then(sortHeaderFields); + const fieldNames = getFieldNameList(data); + const processed = processSchemas(fieldNames); + const filtered = filterExcludedKeys(processed); + + return sortHeaderFields(filtered); } /** RECORD FIELD FUNCTIONS **/ @@ -184,11 +186,11 @@ export const Json2Csv = function(options: FullJson2CsvOptions) { * Unwinds objects in arrays within record objects if the user specifies the * expandArrayObjects option. If not specified, this passes the params * argument through to the next function in the promise chain. - * + * * The `finalPass` parameter is used to trigger one last pass to ensure no more * arrays need to be expanded */ - async function unwindRecordsIfNecessary(params: Json2CsvParams, finalPass = false): Promise { + function unwindRecordsIfNecessary(params: Json2CsvParams, finalPass = false): Json2CsvParams { if (options.unwindArrays) { const originalRecordsLength = params.records.length; @@ -197,30 +199,28 @@ export const Json2Csv = function(options: FullJson2CsvOptions) { params.records = utils.unwind(params.records, headerField); }); - return retrieveHeaderFields(params.records) - .then((headerFields) => { - params.headerFields = headerFields; - - // If we were able to unwind more arrays, then try unwinding again... - if (originalRecordsLength !== params.records.length) { - return unwindRecordsIfNecessary(params); - } - // Otherwise, we didn't unwind any additional arrays, so continue... - - // Run a final time in case the earlier unwinding exposed additional - // arrays to unwind... - if (!finalPass) { - return unwindRecordsIfNecessary(params, true); - } - - // If keys were provided, set the headerFields back to the provided keys after unwinding: - if (options.keys) { - const userSelectedFields = convertKeysToHeaderFields(); - params.headerFields = filterExcludedKeys(userSelectedFields); - } - - return params; - }); + const headerFields = retrieveHeaderFields(params.records); + params.headerFields = headerFields; + + // If we were able to unwind more arrays, then try unwinding again... + if (originalRecordsLength !== params.records.length) { + return unwindRecordsIfNecessary(params); + } + // Otherwise, we didn't unwind any additional arrays, so continue... + + // Run a final time in case the earlier unwinding exposed additional + // arrays to unwind... + if (!finalPass) { + return unwindRecordsIfNecessary(params, true); + } + + // If keys were provided, set the headerFields back to the provided keys after unwinding: + if (options.keys) { + const userSelectedFields = convertKeysToHeaderFields(); + params.headerFields = filterExcludedKeys(userSelectedFields); + } + + return params; } return params; } @@ -403,26 +403,26 @@ export const Json2Csv = function(options: FullJson2CsvOptions) { /** * Internally exported json2csv function */ - async function convert(data: object[]) { + function convert(data: object[]) { // Single document, not an array if (utils.isObject(data) && !data.length) { data = [data]; // Convert to an array of the given document } // Retrieve the heading and then generate the CSV with the keys that are identified - return retrieveHeaderFields(data) - .then((headerFields) => ({ - headerFields, - records: data, - header: '', - recordString: '', - })) - .then(unwindRecordsIfNecessary) - .then(processRecords) - .then(wrapHeaderFields) - .then(trimHeaderFields) - .then(generateCsvHeader) - .then(generateCsvFromComponents); + const headerFields = { + headerFields: retrieveHeaderFields(data), + records: data, + header: '', + recordString: '', + }; + const unwinded = unwindRecordsIfNecessary(headerFields); + const processed = processRecords(unwinded); + const wrapped = wrapHeaderFields(processed); + const trimmed = trimHeaderFields(wrapped); + const generated = generateCsvHeader(trimmed); + + return generateCsvFromComponents(generated); } return { diff --git a/test/csv2json.ts b/test/csv2json.ts index 460207b..fedc5f8 100644 --- a/test/csv2json.ts +++ b/test/csv2json.ts @@ -16,7 +16,7 @@ export function runTests() { jsonTestData: typeof testJsonFiles, csvTestData: typeof testCsvFiles; - describe('csv2json Async/Await Usage', () => { + describe('csv2json Usage', () => { describe('Default Options', () => { beforeEach(() => { options = utils.deepCopy(defaultOptions); @@ -24,192 +24,192 @@ export function runTests() { csvTestData = utils.deepCopy(testCsvFiles); }); - it('should return an empty array when provided an empty csv', async () => { - const json = await csv2json(csvTestData.noData); + it('should return an empty array when provided an empty csv', () => { + const json = csv2json(csvTestData.noData); assert.deepEqual(json, jsonTestData.noData); }); - it('should convert a single basic document from csv to json', async () => { - const json = await csv2json(csvTestData.singleDocument); + it('should convert a single basic document from csv to json', () => { + const json = csv2json(csvTestData.singleDocument); assert.deepEqual(json, jsonTestData.singleDocument); }); - it('should convert csv containing an array representation to json', async () => { - const json = await csv2json(csvTestData.array); + it('should convert csv containing an array representation to json', () => { + const json = csv2json(csvTestData.array); assert.deepEqual(json, jsonTestData.array); }); - it('should convert csv containing a date to json', async () => { - const json = await csv2json(csvTestData.date); + it('should convert csv containing a date to json', () => { + const json = csv2json(csvTestData.date); assert.deepEqual(json, [jsonTestData.date]); }); - it('should convert csv containing null to json', async () => { - const json = await csv2json(csvTestData.null); + it('should convert csv containing null to json', () => { + const json = csv2json(csvTestData.null); assert.deepEqual(json, jsonTestData.null); }); - it('should convert csv containing undefined to json', async () => { - const json = await csv2json(csvTestData.undefined); + it('should convert csv containing undefined to json', () => { + const json = csv2json(csvTestData.undefined); jsonTestData.undefined.colorPreference = undefined; assert.deepEqual(json, [jsonTestData.undefined]); }); - it('should convert csv representing nested json to the correct json structure', async () => { - const json = await csv2json(csvTestData.nested); + it('should convert csv representing nested json to the correct json structure', () => { + const json = csv2json(csvTestData.nested); assert.deepEqual(json, jsonTestData.nested); }); - it('should convert csv representing nested json with a missing field to the correct json structure', async () => { - const json = await csv2json(csvTestData.nestedMissingField); + it('should convert csv representing nested json with a missing field to the correct json structure', () => { + const json = csv2json(csvTestData.nestedMissingField); jsonTestData.nestedMissingField[0].level1.level2.level3 = {level: null}; assert.deepEqual(json, jsonTestData.nestedMissingField); }); - it('should convert csv containing a field with a comma to json', async () => { - const json = await csv2json(csvTestData.comma); + it('should convert csv containing a field with a comma to json', () => { + const json = csv2json(csvTestData.comma); assert.deepEqual(json, jsonTestData.comma); }); - it('should convert csv containing a field with quotes to json', async () => { - const json = await csv2json(csvTestData.quotes); + it('should convert csv containing a field with quotes to json', () => { + const json = csv2json(csvTestData.quotes); assert.deepEqual(json, jsonTestData.quotes); }); - it('should convert csv containing quotes and commas to json', async () => { - const json = await csv2json(csvTestData.quotesAndCommas); + it('should convert csv containing quotes and commas to json', () => { + const json = csv2json(csvTestData.quotesAndCommas); assert.deepEqual(json, jsonTestData.quotesAndCommas); }); - it('should convert csv containing a field with eol characters to json', async () => { - const json = await csv2json(csvTestData.eol); + it('should convert csv containing a field with eol characters to json', () => { + const json = csv2json(csvTestData.eol); assert.deepEqual(json, jsonTestData.eol); }); - it('should ignore empty lines and not convert them to json', async () => { - const json = await csv2json(csvTestData.eol + '\n'); + it('should ignore empty lines and not convert them to json', () => { + const json = csv2json(csvTestData.eol + '\n'); assert.deepEqual(json, jsonTestData.eol); }); - it('should convert csv containing an assortment of values to json', async () => { - const json = await csv2json(csvTestData.assortedValues); + it('should convert csv containing an assortment of values to json', () => { + const json = csv2json(csvTestData.assortedValues); assert.deepEqual(json, jsonTestData.assortedValues); }); - it('should handle an extra new line at the end of the csv', async () => { - const json = await csv2json(csvTestData.extraLine); + it('should handle an extra new line at the end of the csv', () => { + const json = csv2json(csvTestData.extraLine); assert.deepEqual(json, jsonTestData.assortedValues); }); // Test case for #109 - it('should properly handle the cases involving an empty field value', async () => { - const json = await csv2json(csvTestData.csvEmptyLastValue); + it('should properly handle the cases involving an empty field value', () => { + const json = csv2json(csvTestData.csvEmptyLastValue); assert.deepEqual(json, jsonTestData.csvEmptyLastValue); }); // Test case for #115 - it('should properly handle quoted empty field values', async () => { - const json = await csv2json(csvTestData.quotedEmptyFieldValue); + it('should properly handle quoted empty field values', () => { + const json = csv2json(csvTestData.quotedEmptyFieldValue); assert.deepEqual(json, jsonTestData.quotedEmptyFieldValue); }); // Test case for #149 - it('should properly handle invalid parsed values', async () => { - const json = await csv2json(csvTestData.invalidParsedValues); + it('should properly handle invalid parsed values', () => { + const json = csv2json(csvTestData.invalidParsedValues); assert.deepEqual(json, jsonTestData.invalidParsedValues); }); // Test case for #155 - it('should properly convert empty field values if they occur at the end of the csv', async () => { - const json = await csv2json(csvTestData.emptyLastFieldValue); + it('should properly convert empty field values if they occur at the end of the csv', () => { + const json = csv2json(csvTestData.emptyLastFieldValue); assert.deepEqual(json, jsonTestData.emptyLastFieldValue); }); // Test case for #161 - it('should properly convert an empty field value if it occurs at the end of the csv with no EOL at the end', async () => { - const json = await csv2json(csvTestData.lastCharFieldDelimiter); + it('should properly convert an empty field value if it occurs at the end of the csv with no EOL at the end', () => { + const json = csv2json(csvTestData.lastCharFieldDelimiter); assert.deepEqual(json, jsonTestData.emptyLastFieldValue); }); // Test case for #161 - it('should properly convert two empty field values if they occur at the end of the csv with no EOL at the end', async () => { - const json = await csv2json(csvTestData.emptyLastFieldValueNoEol); + it('should properly convert two empty field values if they occur at the end of the csv with no EOL at the end', () => { + const json = csv2json(csvTestData.emptyLastFieldValueNoEol); assert.deepEqual(json, jsonTestData.emptyLastFieldValueNoEol); }); // Test case for #184 - it('should properly convert keys with escaped/nested dots in them', async () => { - const json = await csv2json(csvTestData.nestedDotKeys); + it('should properly convert keys with escaped/nested dots in them', () => { + const json = csv2json(csvTestData.nestedDotKeys); assert.deepEqual(json, jsonTestData.nestedDotKeys); }); // Test case for #184 - it('should properly convert keys with escaped/nested dots in them even when they appear in an array', async () => { - const json = await csv2json(csvTestData.nestedDotKeysWithArray); + it('should properly convert keys with escaped/nested dots in them even when they appear in an array', () => { + const json = csv2json(csvTestData.nestedDotKeysWithArray); assert.deepEqual(json, jsonTestData.nestedDotKeysWithArray); }); // Test case for #184 - it('should properly convert keys with escaped/nested dots in them even when they appear in an expanded, unwound array', async () => { - const json = await csv2json(csvTestData.nestedDotKeysWithArrayExpandedUnwound); + it('should properly convert keys with escaped/nested dots in them even when they appear in an expanded, unwound array', () => { + const json = csv2json(csvTestData.nestedDotKeysWithArrayExpandedUnwound); assert.deepEqual(json, jsonTestData.nestedDotKeysWithArrayExpandedUnwound); }); // Test case for #204 - it('should drop any values with empty column headers', async () => { - const json = await csv2json(csvTestData.emptyColumns); + it('should drop any values with empty column headers', () => { + const json = csv2json(csvTestData.emptyColumns); assert.deepEqual(json, jsonTestData.emptyColumns); }); // Test case for #214 - it('should handle quoted fields with nested EOL characters', async () => { - const json = await csv2json(csvTestData.quotedFieldWithNewline); + it('should handle quoted fields with nested EOL characters', () => { + const json = csv2json(csvTestData.quotedFieldWithNewline); assert.deepEqual(json, jsonTestData.quotedFieldWithNewline); }); }); describe('Error Handling', () => { - it('should throw an error about not having been passed data - null', async () => { + it('should throw an error about not having been passed data - null', () => { try { - await csv2json(null as any); - throw testFailureError; + csv2json(null as any); + throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', `${constants.errors.csv2json.cannotCallOn} null.`); } }); - it('should throw an error about not having been passed data - undefined', async () => { + it('should throw an error about not having been passed data - undefined', () => { try { - await csv2json(undefined as any); + csv2json(undefined as any); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', `${constants.errors.csv2json.cannotCallOn} undefined.`); } }); - it('should throw an error if data is not the proper type - no options provided', async () => { + it('should throw an error if data is not the proper type - no options provided', () => { try { - await csv2json([] as any); + csv2json([] as any); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', constants.errors.csv2json.dataCheckFailure); - + } }); - it('should throw an error if data is not the proper type - options provided', async () => { + it('should throw an error if data is not the proper type - options provided', () => { try { - await csv2json([] as any, {}); + csv2json([] as any, {}); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', constants.errors.csv2json.dataCheckFailure); - + } }); - it('should throw an error when the provided data is of the wrong type', async () => { + it('should throw an error when the provided data is of the wrong type', () => { try { - await csv2json(new Date() as any); + csv2json(new Date() as any); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', constants.errors.csv2json.dataCheckFailure); @@ -248,76 +248,76 @@ export function runTests() { csvTestData = utils.deepCopy(testCsvFiles); }); - it('should use the provided field delimiter and still convert to json', async () => { + it('should use the provided field delimiter and still convert to json', () => { const testFieldDelimiter = '/', replacementRegex = new RegExp(options.delimiter.field, 'g'), testCsv = csvTestData.nested.replace(replacementRegex, testFieldDelimiter); - const json = await csv2json(testCsv, { + const json = csv2json(testCsv, { delimiter: { field: testFieldDelimiter } }); assert.deepEqual(json, jsonTestData.nested); }); - it('should use the provided wrap delimiter and still convert to json', async () => { + it('should use the provided wrap delimiter and still convert to json', () => { const testWrapDelimiter = '\'', replacementRegex = new RegExp(options.delimiter.wrap, 'g'), testCsv = csvTestData.comma.replace(replacementRegex, testWrapDelimiter); - const json = await csv2json(testCsv, { + const json = csv2json(testCsv, { delimiter: { wrap: testWrapDelimiter } }); assert.deepEqual(json, jsonTestData.comma); }); - it('should use the provided end of line delimiter and still convert to json', async () => { + it('should use the provided end of line delimiter and still convert to json', () => { const testEolDelimiter = '\r\n', replacementRegex = new RegExp(options.delimiter.eol, 'g'), testCsv = csvTestData.comma.replace(replacementRegex, testEolDelimiter); - const json = await csv2json(testCsv, { + const json = csv2json(testCsv, { delimiter: { eol: testEolDelimiter } }); assert.deepEqual(json, jsonTestData.comma); }); // Test case for #153 - it('should wrap first column with crlf line break', async () => { - const json = await csv2json(csvTestData.firstColumnWrapCRLF, { + it('should wrap first column with crlf line break', () => { + const json = csv2json(csvTestData.firstColumnWrapCRLF, { delimiter: { eol: '\r\n' } }); assert.deepEqual(json, jsonTestData.firstColumnWrapCRLF); }); - it('should strip the excel byte order mark character, if specified, and convert to json', async () => { - const json = await csv2json(csvTestData.excelBOM, { + it('should strip the excel byte order mark character, if specified, and convert to json', () => { + const json = csv2json(csvTestData.excelBOM, { excelBOM: true }); assert.deepEqual(json, jsonTestData.assortedValues); }); - it('should trim header fields and still convert to json', async () => { - const json = await csv2json(csvTestData.trimHeader, { + it('should trim header fields and still convert to json', () => { + const json = csv2json(csvTestData.trimHeader, { trimHeaderFields: true }); assert.deepEqual(json, jsonTestData.trimmedHeader); }); - it('should trim field values and still convert to json', async () => { - const json = await csv2json(csvTestData.trimFields, { + it('should trim field values and still convert to json', () => { + const json = csv2json(csvTestData.trimFields, { trimFieldValues: true }); assert.deepEqual(json, jsonTestData.trimmedFields); }); - it('should use the provided keys and still convert to json', async () => { - const json = await csv2json(csvTestData.assortedValues, { + it('should use the provided keys and still convert to json', () => { + const json = csv2json(csvTestData.assortedValues, { keys: ['arrayOfStrings', 'object.subField'] }); assert.deepEqual(json, jsonTestData.specifiedKeys); }); - it('should use a custom value parser function when provided', async () => { + it('should use a custom value parser function when provided', () => { const updatedJson = jsonTestData.trimmedFields.map((doc: any) => { doc.arrayOfStrings = 'Parsed Value'; doc.object.subField = 'Parsed Value'; @@ -327,24 +327,24 @@ export function runTests() { return doc; }); - const json = await csv2json(csvTestData.trimmedFields, { + const json = csv2json(csvTestData.trimmedFields, { parseValue: () => 'Parsed Value' }); assert.deepEqual(json, updatedJson); }); - it('should be able to parse CSV with no header line provided', async () => { + it('should be able to parse CSV with no header line provided', () => { const headerlessCsv = csvTestData.unwindWithSpecifiedKeys.split(options.delimiter.eol) .splice(1) .join(options.delimiter.eol); - const json = await csv2json(headerlessCsv, { + const json = csv2json(headerlessCsv, { headerFields: ['data.category', 'data.options.name'] }); assert.deepEqual(json, jsonTestData.unwindWithSpecifiedKeys); }); - it('should be able to parse CSV with no header line provided and different header fields', async () => { + it('should be able to parse CSV with no header line provided and different header fields', () => { const headerlessCsv = csvTestData.unwindWithSpecifiedKeys.split(options.delimiter.eol) .splice(1) .join(options.delimiter.eol), @@ -355,13 +355,13 @@ export function runTests() { return doc; }); - const json = await csv2json(headerlessCsv, { + const json = csv2json(headerlessCsv, { headerFields: ['category', 'product'] }); assert.deepEqual(json, expectedJson); }); - it('should be able to parse CSV with no header line provided and only some of the fields', async () => { + it('should be able to parse CSV with no header line provided and only some of the fields', () => { const headerlessCsv = csvTestData.unwindWithSpecifiedKeys.split(options.delimiter.eol) .splice(1) .join(options.delimiter.eol), @@ -371,7 +371,7 @@ export function runTests() { return doc; }); - const json = await csv2json(headerlessCsv, { + const json = csv2json(headerlessCsv, { headerFields: ['category'] }); assert.deepEqual(json, expectedJson); @@ -394,39 +394,41 @@ export function runTests() { * sent to the catch block. */ - it('should still work with an empty array', async () => { - return csv2json(csvTestData.noData) - .then((json) => { - assert.deepEqual(json, jsonTestData.noData); - }); + it('should still work with an empty array', () => { + const json = csv2json(csvTestData.noData); + + assert.deepEqual(json, jsonTestData.noData); }); - it('should still convert an array of json documents', async () => { - return csv2json(csvTestData.array) - .then((json) => { - assert.deepEqual(json, jsonTestData.array); - }); + it('should still convert an array of json documents', () => { + const json = csv2json(csvTestData.array); + + assert.deepEqual(json, jsonTestData.array); }); - describe('Error Handling', async () => { - it('should still throw an error when not passed data and it should hit the catch block', async () => { - return csv2json(null as any) - .then(() => { - throw testFailureError; - }) - .catch((error) => { - assert.equal(error.message, `${constants.errors.csv2json.cannotCallOn} null.`); - }); + describe('Error Handling', () => { + it('should still throw an error when not passed data and it should hit the catch block', () => { + try { + csv2json(null as any); + } catch (error) { + assert.equal((error as Error).message, `${constants.errors.csv2json.cannotCallOn} null.`); + + return; + } + + throw testFailureError; }); - it('should still throw an error the data is of the wrong type and it should hit the catch block', async () => { - return csv2json(new Date() as any) - .then(() => { - throw testFailureError; - }) - .catch((error) => { - assert.equal(error.message, constants.errors.csv2json.dataCheckFailure); - }); + it('should still throw an error the data is of the wrong type and it should hit the catch block', () => { + try { + csv2json(new Date() as any); + } catch (error) { + assert.equal((error as Error).message, constants.errors.csv2json.dataCheckFailure); + + return; + } + + throw testFailureError; }); }); }); diff --git a/test/json2csv.ts b/test/json2csv.ts index 41425ff..82f1265 100644 --- a/test/json2csv.ts +++ b/test/json2csv.ts @@ -16,7 +16,7 @@ export function runTests() { jsonTestData: typeof testJsonFiles, csvTestData: typeof testCsvFiles; - describe('json2csv Async/Await Usage', () => { + describe('json2csv Usage', () => { describe('Default Options', () => { beforeEach(() => { options = utils.deepCopy(defaultOptions); @@ -24,134 +24,134 @@ export function runTests() { csvTestData = utils.deepCopy(testCsvFiles); }); - it('should convert an empty array to an empty csv', async () => { - const csv = await json2csv(jsonTestData.noData); + it('should convert an empty array to an empty csv', () => { + const csv = json2csv(jsonTestData.noData); assert.equal(csv, csvTestData.noData); }); - it('should convert a single document to csv', async () => { - const csv = await json2csv(jsonTestData.singleDocument); + it('should convert a single document to csv', () => { + const csv = json2csv(jsonTestData.singleDocument); assert.equal(csv, csvTestData.singleDocument); }); - it('should convert objects with arrays to csv correctly', async () => { - const csv = await json2csv(jsonTestData.array); + it('should convert objects with arrays to csv correctly', () => { + const csv = json2csv(jsonTestData.array); assert.equal(csv, csvTestData.array); }); - it('should convert objects with dates to csv correctly', async () => { - const csv = await json2csv([jsonTestData.date]); + it('should convert objects with dates to csv correctly', () => { + const csv = json2csv([jsonTestData.date]); assert.equal(csv, csvTestData.date); }); - it('should convert objects with null to csv correctly', async () => { - const csv = await json2csv(jsonTestData.null); + it('should convert objects with null to csv correctly', () => { + const csv = json2csv(jsonTestData.null); assert.equal(csv, csvTestData.null); }); - it('should convert objects with undefined to csv correctly', async () => { + it('should convert objects with undefined to csv correctly', () => { // Force the value to be set to undefined jsonTestData.undefined.colorPreference = undefined; - const csv = await json2csv([jsonTestData.undefined]); + const csv = json2csv([jsonTestData.undefined]); assert.equal(csv, csvTestData.undefined); }); - it('should convert nested json documents to csv', async () => { - const csv = await json2csv(jsonTestData.nested); + it('should convert nested json documents to csv', () => { + const csv = json2csv(jsonTestData.nested); assert.equal(csv, csvTestData.nested); }); - it('should convert nested json documents with missing fields to csv', async () => { - const csv = await json2csv(jsonTestData.nestedMissingField); + it('should convert nested json documents with missing fields to csv', () => { + const csv = json2csv(jsonTestData.nestedMissingField); assert.equal(csv, csvTestData.nestedMissingField); }); - it('should convert a document with fields containing commas to csv', async () => { - const csv = await json2csv(jsonTestData.comma); + it('should convert a document with fields containing commas to csv', () => { + const csv = json2csv(jsonTestData.comma); assert.equal(csv, csvTestData.comma); }); - it('should convert a document with fields containing quotes to csv', async () => { - const csv = await json2csv(jsonTestData.quotes); + it('should convert a document with fields containing quotes to csv', () => { + const csv = json2csv(jsonTestData.quotes); assert.equal(csv, csvTestData.quotes); }); - it('should convert a document with fields containing quotes and commas to csv', async () => { - const csv = await json2csv(jsonTestData.quotesAndCommas); + it('should convert a document with fields containing quotes and commas to csv', () => { + const csv = json2csv(jsonTestData.quotesAndCommas); assert.equal(csv, csvTestData.quotesAndCommas); }); - it('should convert a document with fields containing an assortment of values to csv', async () => { - const csv = await json2csv(jsonTestData.assortedValues); + it('should convert a document with fields containing an assortment of values to csv', () => { + const csv = json2csv(jsonTestData.assortedValues); assert.equal(csv, csvTestData.assortedValues); }); - it('should convert a document with fields containing eol characters to csv', async () => { - const csv = await json2csv(jsonTestData.eol); + it('should convert a document with fields containing eol characters to csv', () => { + const csv = json2csv(jsonTestData.eol); assert.equal(csv, csvTestData.eol); }); - it('should properly convert the cases involving an empty field value in the csv', async () => { - const csv = await json2csv(jsonTestData.csvEmptyLastValue); + it('should properly convert the cases involving an empty field value in the csv', () => { + const csv = json2csv(jsonTestData.csvEmptyLastValue); assert.equal(csv, csvTestData.csvEmptyLastValue); }); - it('should properly handle headers with the same name as native Map methods', async () => { - const csv = await json2csv(jsonTestData.nativeMapMethod); + it('should properly handle headers with the same name as native Map methods', () => { + const csv = json2csv(jsonTestData.nativeMapMethod); assert.equal(csv, csvTestData.nativeMapMethod); }); // Test case for #184 - it('should properly handle keys with nested dots in them', async () => { - const csv = await json2csv(jsonTestData.nestedDotKeys); + it('should properly handle keys with nested dots in them', () => { + const csv = json2csv(jsonTestData.nestedDotKeys); assert.equal(csv, csvTestData.nestedDotKeys); }); // Test case for #184 - it('should properly handle keys with nested dots in them even when they appear in array fields', async () => { - const csv = await json2csv(jsonTestData.nestedDotKeysWithArray); + it('should properly handle keys with nested dots in them even when they appear in array fields', () => { + const csv = json2csv(jsonTestData.nestedDotKeysWithArray); assert.equal(csv, csvTestData.nestedDotKeysWithArray); }); // Test case for #230 - it('should properly handle falsy values in documents', async () => { - const csv = await json2csv(jsonTestData.falsyValues); + it('should properly handle falsy values in documents', () => { + const csv = json2csv(jsonTestData.falsyValues); assert.equal(csv, csvTestData.falsyValues); }); }); describe('Error Handling', () => { - it('should throw an error when the provided data is of the wrong type', async () => { + it('should throw an error when the provided data is of the wrong type', () => { try { - await json2csv(undefined as any); + json2csv(undefined as any); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', `${constants.errors.json2csv.cannotCallOn} undefined.`); } }); - it('should throw an error about not having been passed data - null', async () => { + it('should throw an error about not having been passed data - null', () => { try { - await json2csv(null as any); + json2csv(null as any); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', `${constants.errors.json2csv.cannotCallOn} null.`); } }); - it('should throw an error about not having been passed data - undefined', async () => { + it('should throw an error about not having been passed data - undefined', () => { try { - await json2csv(undefined as any); + json2csv(undefined as any); throw testFailureError; } catch (error) { assert.equal(error instanceof Error ? error.message : '', `${constants.errors.json2csv.cannotCallOn} undefined.`); } }); - it('should throw an error if the documents do not have the same schema', async () => { + it('should throw an error if the documents do not have the same schema', () => { try { - await json2csv(jsonTestData.nestedMissingField, { + json2csv(jsonTestData.nestedMissingField, { checkSchemaDifferences: true }); throw testFailureError; @@ -192,106 +192,106 @@ export function runTests() { csvTestData = utils.deepCopy(testCsvFiles); }); - it('should use the provided field delimiter and still convert to json', async () => { + it('should use the provided field delimiter and still convert to json', () => { const testFieldDelimiter = '/', replacementRegex = new RegExp(options.delimiter.field, 'g'), testCsv = csvTestData.nested.replace(replacementRegex, testFieldDelimiter); - const csv = await json2csv(jsonTestData.nested, { + const csv = json2csv(jsonTestData.nested, { delimiter: { field: testFieldDelimiter } }); assert.equal(csv, testCsv); }); - it('should use the provided wrap delimiter and still convert to json', async () => { + it('should use the provided wrap delimiter and still convert to json', () => { const testWrapDelimiter = '\'', replacementRegex = new RegExp(options.delimiter.wrap, 'g'), testCsv = csvTestData.comma.replace(replacementRegex, testWrapDelimiter); - const csv = await json2csv(jsonTestData.comma, { + const csv = json2csv(jsonTestData.comma, { delimiter: { wrap: testWrapDelimiter } }); assert.equal(csv, testCsv); }); - it('should use the provided end of line delimiter and still convert to json', async () => { + it('should use the provided end of line delimiter and still convert to json', () => { const testEolDelimiter = '\r\n', replacementRegex = new RegExp(options.delimiter.eol, 'g'), testCsv = csvTestData.comma.replace(replacementRegex, testEolDelimiter); - const csv = await json2csv(jsonTestData.comma, { + const csv = json2csv(jsonTestData.comma, { delimiter: { eol: testEolDelimiter } }); assert.equal(csv, testCsv); }); - it('should include an excel byte order mark character at the beginning of the csv', async () => { - const csv = await json2csv(jsonTestData.assortedValues, { + it('should include an excel byte order mark character at the beginning of the csv', () => { + const csv = json2csv(jsonTestData.assortedValues, { excelBOM: true }); assert.equal(csv, csvTestData.excelBOM); }); - it('should not prepend a header if it the options indicate not to add one to the csv', async () => { - const csv = await json2csv(jsonTestData.assortedValues, { + it('should not prepend a header if it the options indicate not to add one to the csv', () => { + const csv = json2csv(jsonTestData.assortedValues, { prependHeader: false }); assert.equal(csv, csvTestData.noHeader); }); - it('should sort the header in the csv', async () => { - const csv = await json2csv(jsonTestData.assortedValues, { + it('should sort the header in the csv', () => { + const csv = json2csv(jsonTestData.assortedValues, { sortHeader: true }); assert.equal(csv, csvTestData.sortedHeader); }); - it('should sort the header with a custom function in the csv', async () => { - const csv = await json2csv(jsonTestData.assortedValues, { + it('should sort the header with a custom function in the csv', () => { + const csv = json2csv(jsonTestData.assortedValues, { sortHeader: (a, b) => b.localeCompare(a) }); assert.equal(csv, csvTestData.sortedHeaderCustom); }); - it('should trim the header fields when specified', async () => { - const csv = await json2csv(jsonTestData.trimHeader, { + it('should trim the header fields when specified', () => { + const csv = json2csv(jsonTestData.trimHeader, { trimHeaderFields: true }); assert.equal(csv, csvTestData.trimmedHeader); }); - it('should trim the field values when specified', async () => { - const csv = await json2csv(jsonTestData.trimFields, { + it('should trim the field values when specified', () => { + const csv = json2csv(jsonTestData.trimFields, { trimFieldValues: true }); assert.equal(csv, csvTestData.trimmedFields); }); - it('should check schema differences when specified - no data', async () => { - const csv = await json2csv(jsonTestData.noData, { + it('should check schema differences when specified - no data', () => { + const csv = json2csv(jsonTestData.noData, { checkSchemaDifferences: true }); assert.equal(csv, csvTestData.noData); }); - it('should check schema differences when specified - same schema', async () => { - const csv = await json2csv(jsonTestData.quotesAndCommas, { + it('should check schema differences when specified - same schema', () => { + const csv = json2csv(jsonTestData.quotesAndCommas, { checkSchemaDifferences: true }); assert.equal(csv, csvTestData.quotesAndCommas); }); - it('should use the specified keys, if provided', async () => { - const csv = await json2csv(jsonTestData.assortedValues, { + it('should use the specified keys, if provided', () => { + const csv = json2csv(jsonTestData.assortedValues, { keys: ['arrayOfStrings', 'object.subField'] }); assert.equal(csv, csvTestData.specifiedKeys); }); - it('should use the specified empty field value, if provided', async () => { + it('should use the specified empty field value, if provided', () => { jsonTestData.emptyFieldValues[0].number = undefined; - - const csv = await json2csv(jsonTestData.emptyFieldValues, { + + const csv = json2csv(jsonTestData.emptyFieldValues, { emptyFieldValue: '' }); @@ -304,8 +304,8 @@ export function runTests() { assert.equal(csv, expectedCsv); }); - it('should expand array objects when specified - without objects', async () => { - const csv = await json2csv(jsonTestData.array, { + it('should expand array objects when specified - without objects', () => { + const csv = json2csv(jsonTestData.array, { expandArrayObjects: true }); const expectedCsv = csvTestData.array @@ -314,76 +314,76 @@ export function runTests() { assert.equal(csv, expectedCsv); }); - it('should expand array objects when specified - with an object containing an empty array', async () => { + it('should expand array objects when specified - with an object containing an empty array', () => { // Change the features array to be empty jsonTestData.arrayObjects[1].features = []; - const csv = await json2csv(jsonTestData.arrayObjects, { + const csv = json2csv(jsonTestData.arrayObjects, { expandArrayObjects: true }); assert.equal(csv, csvTestData.arrayObjects.replace('testing', '')); }); - it('should expand array objects when specified - with objects containing an array of objects', async () => { - const csv = await json2csv(jsonTestData.arrayMixedObjNonObj, { + it('should expand array objects when specified - with objects containing an array of objects', () => { + const csv = json2csv(jsonTestData.arrayMixedObjNonObj, { expandArrayObjects: true }); assert.equal(csv, csvTestData.arrayMixedObjNonObj); }); - it('should expand array objects when specified - with objects containing an array of objects', async () => { - const csv = await json2csv(jsonTestData.arrayObjects, { + it('should expand array objects when specified - with objects containing an array of objects', () => { + const csv = json2csv(jsonTestData.arrayObjects, { expandArrayObjects: true }); assert.equal(csv, csvTestData.arrayObjects); }); - it('should handle unwinding empty array values when specified', async () => { - const csv = await json2csv(jsonTestData.unwindEmptyArray, { + it('should handle unwinding empty array values when specified', () => { + const csv = json2csv(jsonTestData.unwindEmptyArray, { unwindArrays: true }); assert.equal(csv, csvTestData.unwindEmptyArray); }); - it('should unwind array values when specified', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should unwind array values when specified', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true }); assert.equal(csv, csvTestData.unwind); }); - it('should unwind nested array values when the earlier array has a length of 1', async () => { - const csv = await json2csv(jsonTestData.arraySingleArray, { + it('should unwind nested array values when the earlier array has a length of 1', () => { + const csv = json2csv(jsonTestData.arraySingleArray, { unwindArrays: true }); assert.equal(csv, csvTestData.arraySingleArray); }); - it('should unwind array values when specified - with keys specified', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should unwind array values when specified - with keys specified', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true, keys: ['data.category', 'data.options.name'] }); assert.equal(csv, csvTestData.unwindWithSpecifiedKeys); }); - it('should use the locale format when specified', async () => { - const csv = await json2csv(jsonTestData.localeFormat, { + it('should use the locale format when specified', () => { + const csv = json2csv(jsonTestData.localeFormat, { useLocaleFormat: true, unwindArrays: true }); assert.equal(csv, csvTestData.localeFormat); }); - it('should convert objects with dates to iso8601 format correctly', async () => { + it('should convert objects with dates to iso8601 format correctly', () => { // Convert to a date since the `dob` value is imported as a string by default for some reason jsonTestData.date.dob = new Date('1990-01-01T05:00:00.000Z'); - const csv = await json2csv([jsonTestData.date], { useDateIso8601Format: true }); + const csv = json2csv([jsonTestData.date], { useDateIso8601Format: true }); assert.equal(csv, csvTestData.date); }); - it('should allow keys to be specified without titles', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should allow keys to be specified without titles', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true, keys: [ {field: 'data.category'}, @@ -393,8 +393,8 @@ export function runTests() { assert.equal(csv, csvTestData.unwindWithSpecifiedKeys); }); - it('should allow titles to be specified for certain keys, but not others when not unwinding arrays', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should allow titles to be specified for certain keys, but not others when not unwinding arrays', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: false, keys: [ {field: 'data.category', title: 'Category'}, @@ -404,8 +404,8 @@ export function runTests() { assert.equal(csv, csvTestData.withSpecifiedKeys.replace('data.category,data.options.name', 'Category,data.options.name')); }); - it('should allow titles to be specified for certain keys, but not others', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should allow titles to be specified for certain keys, but not others', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true, keys: [ {field: 'data.category', title: 'Category'}, @@ -415,8 +415,8 @@ export function runTests() { assert.equal(csv, csvTestData.unwindWithSpecifiedKeys.replace('data.category,data.options.name', 'Category,data.options.name')); }); - it('should allow titles to be specified', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should allow titles to be specified', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: false, keys: [ {field: 'data.category', title: 'Category'}, @@ -426,8 +426,8 @@ export function runTests() { assert.equal(csv, csvTestData.withSpecifiedKeys.replace('data.category,data.options.name', 'Category,Option Name')); }); - it('should allow titles to be specified when not unwinding arrays', async () => { - const csv = await json2csv(jsonTestData.unwind, { + it('should allow titles to be specified when not unwinding arrays', () => { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true, keys: [ {field: 'data.category', title: 'Category'}, @@ -437,13 +437,13 @@ export function runTests() { assert.equal(csv, csvTestData.unwindWithSpecifiedKeys.replace('data.category,data.options.name', 'Category,Option Name')); }); - it('should exclude specified keys from the output', async () => { + it('should exclude specified keys from the output', () => { // Change the features array to be empty const updatedCsvPerOptions = csvTestData.arrayObjects.replace('features.cons,', '') .replace('"[""cost"",""time""]",', '') .replace(',,,', ',,'); - const csv = await json2csv(jsonTestData.arrayObjects, { + const csv = json2csv(jsonTestData.arrayObjects, { expandArrayObjects: true, keys: ['name', 'features.name', 'features.pros', 'features.cons', 'downloads'], excludeKeys: ['features.cons'] @@ -451,7 +451,7 @@ export function runTests() { assert.equal(csv, updatedCsvPerOptions); }); - it('should exclude specified keys from the output when unwinding arrays', async () => { + it('should exclude specified keys from the output when unwinding arrays', () => { const updatedCsv = csvTestData.unwind.replace(',data.options.name', '') .replace(/,MacBook (Pro|Air) \d+/g, '') .replace(/,(Super|Turbo)charger/g, '') @@ -459,47 +459,47 @@ export function runTests() { .replace('5cf7ca3616c91100018844af,Computers\n', '') .replace('5cf7ca3616c91100018844bf,Cars\n', ''); - const csv = await json2csv(jsonTestData.unwind, { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true, excludeKeys: ['data.options.name', 'data.options'] }); assert.equal(csv, updatedCsv); }); - it('should exclude specified deeply nested key from the output when unwinding arrays', async () => { + it('should exclude specified deeply nested key from the output when unwinding arrays', () => { const updatedCsv = csvTestData.unwind.replace(',data.options.name', '') .replace(/,MacBook (Pro|Air) \d+/g, '') .replace(/,(Super|Turbo)charger/g, ''); - const csv = await json2csv(jsonTestData.unwind, { + const csv = json2csv(jsonTestData.unwind, { unwindArrays: true, excludeKeys: ['data.options.name'] }); assert.equal(csv, updatedCsv); }); - it('should use a custom value parser function when provided', async () => { + it('should use a custom value parser function when provided', () => { const updatedCsv = csvTestData.trimmedFields.split('\n'); const textRow = 'Parsed Value,Parsed Value,Parsed Value,Parsed Value,Parsed Value'; updatedCsv[1] = textRow; updatedCsv[2] = textRow; const expectedCsv = updatedCsv.join('\n'); - const csv = await json2csv(jsonTestData.trimmedFields, { + const csv = json2csv(jsonTestData.trimmedFields, { parseValue: () => 'Parsed Value' }); assert.equal(csv, expectedCsv); }); - it('should pass the default value parser to custom value parser function when provided', async () => { - const csv = await json2csv(jsonTestData.trimmedFields, { + it('should pass the default value parser to custom value parser function when provided', () => { + const csv = json2csv(jsonTestData.trimmedFields, { parseValue: (fieldValue, defaultParser) => defaultParser(fieldValue) }); assert.equal(csv, csvTestData.trimmedFields); }); - it('should wrap boolean values in wrap delimiters, if specified', async () => { - const csv = await json2csv(jsonTestData.emptyFieldValues, { + it('should wrap boolean values in wrap delimiters, if specified', () => { + const csv = json2csv(jsonTestData.emptyFieldValues, { emptyFieldValue: '', wrapBooleans: true }); @@ -510,83 +510,83 @@ export function runTests() { .replace(/\n"",/g, '\n,') .replace(/false/g, '"false"') .replace(/true/g, '"true"'); - + assert.equal(csv, expectedCsv); }); // Test cases for https://github.com/mrodrig/json-2-csv/issues/209 - it('should left trim equals (=) if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: '=Bob'}], { + it('should left trim equals (=) if preventCsvInjection is specified', () => { + const csv = json2csv([{name: '=Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should left trim plus (+) if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: '+Bob'}], { + it('should left trim plus (+) if preventCsvInjection is specified', () => { + const csv = json2csv([{name: '+Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should left trim minus (-) if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: '-Bob'}], { + it('should left trim minus (-) if preventCsvInjection is specified', () => { + const csv = json2csv([{name: '-Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should left trim at (@) if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: '@Bob'}], { + it('should left trim at (@) if preventCsvInjection is specified', () => { + const csv = json2csv([{name: '@Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should left trim tab (0x09) if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: String.fromCharCode(9) + 'Bob'}], { + it('should left trim tab (0x09) if preventCsvInjection is specified', () => { + const csv = json2csv([{name: String.fromCharCode(9) + 'Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should left trim carriage return (0x0D) if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: String.fromCharCode(13) + 'Bob'}], { + it('should left trim carriage return (0x0D) if preventCsvInjection is specified', () => { + const csv = json2csv([{name: String.fromCharCode(13) + 'Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should left trim a combination of csv injection characters if preventCsvInjection is specified', async () => { - const csv = await json2csv([{name: String.fromCharCode(9) + String.fromCharCode(13) + '=+-@Bob'}], { + it('should left trim a combination of csv injection characters if preventCsvInjection is specified', () => { + const csv = json2csv([{name: String.fromCharCode(9) + String.fromCharCode(13) + '=+-@Bob'}], { preventCsvInjection: true }); - + const expectedCsv = 'name\nBob'; - + assert.equal(csv, expectedCsv); }); - it('should not alter numbers by removing minus (-) even if preventCsvInjection is specified', async () => { - const csv = await json2csv([{temperature: -10}], { + it('should not alter numbers by removing minus (-) even if preventCsvInjection is specified', () => { + const csv = json2csv([{temperature: -10}], { preventCsvInjection: true }); @@ -595,9 +595,9 @@ export function runTests() { assert.equal(csv, expectedCsv); }); - it('should not left trim a combination of csv injection characters if preventCsvInjection is not specified', async () => { + it('should not left trim a combination of csv injection characters if preventCsvInjection is not specified', () => { const originalValue = String.fromCharCode(9) + String.fromCharCode(13) + '=+-@Bob'; - const csv = await json2csv([{name: originalValue}], {}); + const csv = json2csv([{name: originalValue}], {}); const expectedCsv = `name\n"${originalValue}"`; @@ -605,8 +605,8 @@ export function runTests() { }); // Test case for #184 - it('should handle keys with nested dots when expanding and unwinding arrays', async () => { - const csv = await json2csv(jsonTestData.nestedDotKeysWithArrayExpandedUnwound, { + it('should handle keys with nested dots when expanding and unwinding arrays', () => { + const csv = json2csv(jsonTestData.nestedDotKeysWithArrayExpandedUnwound, { expandArrayObjects: true, unwindArrays: true }); @@ -617,8 +617,8 @@ export function runTests() { assert.equal(csv, expectedCsv); }); - it('should respect the expandNestedObjects option being set to false', async () => { - const csv = await json2csv(jsonTestData.nested, { + it('should respect the expandNestedObjects option being set to false', () => { + const csv = json2csv(jsonTestData.nested, { expandNestedObjects: false, }); @@ -642,40 +642,42 @@ export function runTests() { * sent to the catch block. */ - it('should still work with an empty array', async () => { - return json2csv(jsonTestData.noData) - .then((csv) => { - assert.equal(csv, csvTestData.noData); - }); + it('should still work with an empty array', () => { + const csv = json2csv(jsonTestData.noData); + + assert.equal(csv, csvTestData.noData); }); - it('should still work with an array of documents', async () => { - return json2csv(jsonTestData.array) - .then((csv) => { - assert.equal(csv, csvTestData.array); - }); + it('should still work with an array of documents', () => { + const csv = json2csv(jsonTestData.array); + + assert.equal(csv, csvTestData.array); }); }); describe('Error Handling', () => { - it('should throw an error about not having been passed data', async () => { - return json2csv(undefined as any) - .then(() => { - throw testFailureError; - }) - .catch((err) => { - assert.equal(err.message, `${constants.errors.json2csv.cannotCallOn} undefined.`); - }); + it('should throw an error about not having been passed data', () => { + try { + json2csv(undefined as any); + } catch (error) { + assert.equal((error as Error).message, `${constants.errors.json2csv.cannotCallOn} undefined.`); + + return; + } + + throw testFailureError; }); - it('should throw an error about not having been passed data - null', async () => { - return json2csv(null as any) - .then(() => { - throw testFailureError; - }) - .catch((err) => { - assert.equal(err.message, `${constants.errors.json2csv.cannotCallOn} null.`); - }); + it('should throw an error about not having been passed data - null', () => { + try { + json2csv(null as any); + } catch (error) { + assert.equal((error as Error).message, `${constants.errors.json2csv.cannotCallOn} null.`); + + return; + } + + throw testFailureError; }); }); });