Skip to content

Commit e2e5a67

Browse files
committed
implement basic test for csv parsing
1 parent 78da75b commit e2e5a67

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

test/csv.test.cjs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const assert = require('assert');
2+
const fs = require('fs');
3+
const { parse } = require('csv-parse');
4+
const { promisify } = require('util');
5+
6+
const parseCSV = async (filePath) => {
7+
return new Promise((resolve, reject) => {
8+
const records = [];
9+
fs.createReadStream(filePath)
10+
.pipe(parse({ columns: true }))
11+
.on('data', (data) => records.push(data))
12+
.on('end', () => resolve(records))
13+
.on('error', (error) => reject(error));
14+
});
15+
};
16+
17+
describe('CSV Parsing', function() {
18+
it('should parse a valid CSV file correctly', async function() {
19+
// Create a temporary CSV file using a string or a fixture
20+
const csvData = `name,age\nAlice,30\nBob,25\n`;
21+
const tempFile = './test/temp.csv';
22+
fs.writeFileSync(tempFile, csvData);
23+
24+
const records = await parseCSV(tempFile);
25+
assert.strictEqual(records.length, 2);
26+
assert.strictEqual(records[0].name, 'Alice');
27+
assert.strictEqual(records[1].age, '25');
28+
29+
// Clean up
30+
fs.unlinkSync(tempFile);
31+
});
32+
33+
it('should throw an error for a malformed CSV', async function() {
34+
// Intentionally malform the CSV to expect a parsing error
35+
const badCsv = `name,age\nAlice\nBob,25\n`;
36+
const tempFile = './test/temp_bad.csv';
37+
fs.writeFileSync(tempFile, badCsv);
38+
39+
try {
40+
await parseCSV(tempFile);
41+
// If no error is thrown, force a failure.
42+
assert.fail('Expected error was not thrown');
43+
} catch (err) {
44+
assert.ok(err, 'Error should be thrown for malformed CSV');
45+
} finally {
46+
fs.unlinkSync(tempFile);
47+
}
48+
});
49+
});

0 commit comments

Comments
 (0)