From 9db378de2fe679b3a591ad16c2de85501ccc838d Mon Sep 17 00:00:00 2001 From: Kenny Daniel Date: Tue, 28 May 2024 14:24:12 -0700 Subject: [PATCH] toJson tests --- src/utils.js | 4 +--- test/utils.test.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 test/utils.test.js diff --git a/src/utils.js b/src/utils.js index 5f7197e..75cfed4 100644 --- a/src/utils.js +++ b/src/utils.js @@ -1,7 +1,5 @@ /** - * Replace bigints with numbers. - * When parsing parquet files, bigints are used to represent 64-bit integers. - * However, JSON does not support bigints, so it's helpful to convert to numbers. + * Replace bigint, date, etc with legal JSON types. * * @param {any} obj object to convert * @returns {unknown} converted object diff --git a/test/utils.test.js b/test/utils.test.js new file mode 100644 index 0000000..8906a21 --- /dev/null +++ b/test/utils.test.js @@ -0,0 +1,39 @@ +import { describe, expect, it } from 'vitest' +import { toJson } from '../src/utils.js' + +describe('toJson', () => { + it('convert undefined to null', () => { + expect(toJson(undefined)).toBe(null) + expect(toJson(null)).toBe(null) + }) + + it('convert bigint to number', () => { + expect(toJson(BigInt(123))).toBe(123) + expect(toJson([BigInt(123), BigInt(456)])).toEqual([123, 456]) + expect(toJson({ a: BigInt(123), b: { c: BigInt(456) } })).toEqual({ a: 123, b: { c: 456 } }) + }) + + it('convert Uint8Array to array of numbers', () => { + expect(toJson(new Uint8Array([1, 2, 3]))).toEqual([1, 2, 3]) + }) + + it('convert Date to ISO string', () => { + const date = new Date('2023-05-27T00:00:00Z') + expect(toJson(date)).toBe(date.toISOString()) + }) + + it('ignore undefined properties in objects', () => { + expect(toJson({ a: undefined, b: BigInt(123) })).toEqual({ b: 123 }) + }) + + it('return null in objects unchanged', () => { + expect(toJson({ a: null })).toEqual({ a: null }) + expect(toJson([null])).toEqual([null]) + }) + + it('return other types unchanged', () => { + expect(toJson('string')).toBe('string') + expect(toJson(123)).toBe(123) + expect(toJson(true)).toBe(true) + }) +})