Skip to content

Commit

Permalink
fix(csv2json): throw on invalid input. add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
gadicc committed Feb 4, 2021
1 parent 72e3d71 commit 9a4d31a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
47 changes: 47 additions & 0 deletions src/lib/cs2json.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import csv2json from './csv2json';

/*
const toBeType = require('jest-tobetype').toBeType;
expect.extend({
toBeType,
});
*/

/*
const toBeType = require("jest-tobetype");
expect.extend(toBeType);
*/

describe('csv2json', () => {

it('handles historical input', () => {
const csv =
"Date,Open,High,Low,Close,Adj Close,Volume\n" +
"2020-10-29,112.370003,116.930000,112.199997,115.320000,115.121384,146129200\n" +
"2020-10-30,111.059998,111.989998,107.720001,108.860001,108.672516,190272600";

const obj = csv2json(csv);
expect(obj.length).toBe(2);

// camelcase
const headers = Object.keys(obj[0]);
expect(headers[0]).toBe('date');
expect(headers[5]).toBe('adjClose');

expect(obj[0].date).toBeInstanceOf(Date);
expect(obj[0].open).toBeType('number');
});

it("returns anything else - not actually used in historical", () => {
const csv = "string\nstring";
const obj = csv2json(csv);
expect(obj[0].string).toBeType('string');
});

it('throws on weird file (no newlines)', () => {
const csv ="one line file";
expect(() => csv2json(csv)).toThrow(/No newlines/);
});

});
2 changes: 1 addition & 1 deletion src/lib/csv2json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function convert(input: any) {

export default function csv2json(csv: string): Array<any> {
const lines = csv.split('\n');
if (lines.length === 0)
if (lines.length === 1)
throw new Error("No newlines in: " + csv);

const headers = (lines.shift() as string).split(DELIMITER).map(camelize);
Expand Down

0 comments on commit 9a4d31a

Please sign in to comment.