1
0
mirror of https://github.com/sasjs/adapter.git synced 2026-01-18 09:30:06 +00:00

chore(*): add tests

This commit is contained in:
Krishna Acondy
2021-05-06 13:59:33 +01:00
parent 5543f467e6
commit 665734b168
2 changed files with 41 additions and 24 deletions

View File

@@ -40,4 +40,36 @@ describe('convertToCsv', () => {
expect(convertToCSV(data)).toEqual(expectedOutput) expect(convertToCSV(data)).toEqual(expectedOutput)
}) })
it('should convert values with mixed quotes', () => {
const data = [{ foo: `',''`, bar: `","` }]
const expectedOutput = `foo:$4. bar:$3.\r\n"',''",""","""`
expect(convertToCSV(data)).toEqual(expectedOutput)
})
it('should convert values with mixed quotes', () => {
const data = [{ foo: `','`, bar: `,"` }]
const expectedOutput = `foo:$3. bar:$2.\r\n"','",","""`
expect(convertToCSV(data)).toEqual(expectedOutput)
})
it('should convert values with mixed quotes', () => {
const data = [{ foo: `"`, bar: `'` }]
const expectedOutput = `foo:$1. bar:$1.\r\n"""","'"`
expect(convertToCSV(data)).toEqual(expectedOutput)
})
it('should convert values with mixed quotes', () => {
const data = [{ foo: `,`, bar: `',` }]
const expectedOutput = `foo:$1. bar:$2.\r\n",","',"`
expect(convertToCSV(data)).toEqual(expectedOutput)
})
}) })

View File

@@ -69,35 +69,20 @@ export const convertToCSV = (data: any) => {
csvTest = data.map((row: any) => { csvTest = data.map((row: any) => {
const fields = Object.keys(row).map((fieldName, index) => { const fields = Object.keys(row).map((fieldName, index) => {
let value let value
let containsSpecialChar = false
const currentCell = row[fieldName] const currentCell = row[fieldName]
if (JSON.stringify(currentCell).search(/(\\t|\\n|\\r)/gm) > -1) { // stringify with replacer converts null values to empty strings
containsSpecialChar = true // also wraps the value in double quotes
} value = JSON.stringify(currentCell, replacer).replace(/\\\"/g, `""`)
value = JSON.stringify(currentCell, replacer)
value = value.replace(/\\\\/gm, '\\') value = value.replace(/\\\\/gm, '\\')
if (containsSpecialChar) { if (
if (value.includes(',') || value.includes('"')) { value.substring(1, value.length - 1).search(/(\\t|\\n|\\r|,|\'|\")/gm) <
value = '"' + value + '"' 0
} ) {
} else { // Remove wrapping quotes for values that don't contain special characters
if ( value = value.substring(1, value.length - 1)
!value.includes(',') &&
value.includes('"') &&
!value.includes('\\"')
) {
value = value.substring(1, value.length - 1)
}
if (value.includes("'")) {
value = '"' + value + '"'
}
value = value.replace(/\\"/gm, '""')
} }
value = value.replace(/\r\n/gm, '\n') value = value.replace(/\r\n/gm, '\n')