|
| 1 | +import { extractIdentifiers, parseCsvText, toParsedCsv } from 'common/utils/csv' |
| 2 | + |
| 3 | +describe('parseCsvText', () => { |
| 4 | + const cases: [string, string, string[][]][] = [ |
| 5 | + ['single column', 'a\nb\nc', [['a'], ['b'], ['c']]], |
| 6 | + [ |
| 7 | + 'multiple columns', |
| 8 | + 'id,email\n1,a@b.com', |
| 9 | + [ |
| 10 | + ['id', 'email'], |
| 11 | + ['1', 'a@b.com'], |
| 12 | + ], |
| 13 | + ], |
| 14 | + ['crlf line endings', 'a\r\nb\r\n', [['a'], ['b']]], |
| 15 | + [ |
| 16 | + 'quoted fields with commas and escaped quotes', |
| 17 | + '"a,b","say ""hi"""\nc,d', |
| 18 | + [ |
| 19 | + ['a,b', 'say "hi"'], |
| 20 | + ['c', 'd'], |
| 21 | + ], |
| 22 | + ], |
| 23 | + ['blank lines dropped', 'a\n\n \nb', [['a'], ['b']]], |
| 24 | + ['empty input', '', []], |
| 25 | + ] |
| 26 | + |
| 27 | + test.each(cases)('%s', (_, input, expected) => { |
| 28 | + expect(parseCsvText(input)).toEqual(expected) |
| 29 | + }) |
| 30 | +}) |
| 31 | + |
| 32 | +describe('toParsedCsv', () => { |
| 33 | + const rawRows = [ |
| 34 | + ['id', 'email'], |
| 35 | + ['1', 'a@b.com'], |
| 36 | + ] |
| 37 | + |
| 38 | + test('with headers, first row becomes column names', () => { |
| 39 | + expect(toParsedCsv(rawRows, true)).toEqual({ |
| 40 | + columns: ['id', 'email'], |
| 41 | + rows: [['1', 'a@b.com']], |
| 42 | + }) |
| 43 | + }) |
| 44 | + |
| 45 | + test('without headers, generates Column N names', () => { |
| 46 | + expect(toParsedCsv(rawRows, false)).toEqual({ |
| 47 | + columns: ['Column 1', 'Column 2'], |
| 48 | + rows: rawRows, |
| 49 | + }) |
| 50 | + }) |
| 51 | + |
| 52 | + test('blank header cells fall back to Column N', () => { |
| 53 | + expect(toParsedCsv([['id', ''], ['1']], true).columns).toEqual([ |
| 54 | + 'id', |
| 55 | + 'Column 2', |
| 56 | + ]) |
| 57 | + }) |
| 58 | + |
| 59 | + test('empty input yields no columns or rows', () => { |
| 60 | + expect(toParsedCsv([], true)).toEqual({ columns: [], rows: [] }) |
| 61 | + }) |
| 62 | +}) |
| 63 | + |
| 64 | +describe('extractIdentifiers', () => { |
| 65 | + test('trims values and counts empty and duplicate rows', () => { |
| 66 | + const rows = [['a'], [' b '], [''], ['a'], [' '], ['b']] |
| 67 | + expect(extractIdentifiers(rows, 0)).toEqual({ |
| 68 | + duplicateCount: 2, |
| 69 | + emptyCount: 2, |
| 70 | + identifiers: ['a', 'b'], |
| 71 | + }) |
| 72 | + }) |
| 73 | + |
| 74 | + test('missing cells in short rows count as empty', () => { |
| 75 | + expect(extractIdentifiers([['x', 'y'], ['z']], 1)).toEqual({ |
| 76 | + duplicateCount: 0, |
| 77 | + emptyCount: 1, |
| 78 | + identifiers: ['y'], |
| 79 | + }) |
| 80 | + }) |
| 81 | +}) |
0 commit comments