|
| 1 | +import { bigIntReplacer, convertBigIntToString } from "./bigint-util" |
| 2 | + |
| 3 | +const BIG_INT_VALUE = BigInt(10 ** 20) |
| 4 | +const BIG_INT_STRING_VALUE = "100000000000000000000" |
| 5 | + |
| 6 | +describe("bigIntReplacer", () => { |
| 7 | + it("should convert bigint to string", () => { |
| 8 | + const sut = { |
| 9 | + key: BIG_INT_VALUE, |
| 10 | + nestedKey: { |
| 11 | + key: BIG_INT_VALUE, |
| 12 | + }, |
| 13 | + } |
| 14 | + const result = JSON.stringify(sut, bigIntReplacer) |
| 15 | + expect(result).toBe(`{"key":"${BIG_INT_STRING_VALUE}","nestedKey":{"key":"${BIG_INT_STRING_VALUE}"}}`) |
| 16 | + }) |
| 17 | + |
| 18 | + it("should return value as is if not a bigint", () => { |
| 19 | + const sut = { |
| 20 | + key: 100, |
| 21 | + } |
| 22 | + const result = JSON.stringify(sut, bigIntReplacer) |
| 23 | + expect(result).toBe('{"key":100}') |
| 24 | + }) |
| 25 | +}) |
| 26 | + |
| 27 | +describe("convertBigIntToString", () => { |
| 28 | + it("should convert bigint to string", () => { |
| 29 | + const result = convertBigIntToString(BIG_INT_VALUE) |
| 30 | + expect(result).toBe(BIG_INT_STRING_VALUE) |
| 31 | + }) |
| 32 | + |
| 33 | + it("should convert bigint in array to string", () => { |
| 34 | + const result = convertBigIntToString([BIG_INT_VALUE, 123]) |
| 35 | + expect(result).toEqual([BIG_INT_STRING_VALUE, 123]) |
| 36 | + }) |
| 37 | + |
| 38 | + it("should convert bigint in object to string", () => { |
| 39 | + const result = convertBigIntToString({ key: BIG_INT_VALUE, anotherKey: 123 }) |
| 40 | + expect(result).toEqual({ key: BIG_INT_STRING_VALUE, anotherKey: 123 }) |
| 41 | + }) |
| 42 | + |
| 43 | + it("should handle nested structures", () => { |
| 44 | + const data = { |
| 45 | + key: BIG_INT_VALUE, |
| 46 | + nested: { |
| 47 | + anotherKey: BIG_INT_VALUE, |
| 48 | + array: [BIG_INT_VALUE, 123], |
| 49 | + }, |
| 50 | + } |
| 51 | + const expected = { |
| 52 | + key: BIG_INT_STRING_VALUE, |
| 53 | + nested: { |
| 54 | + anotherKey: BIG_INT_STRING_VALUE, |
| 55 | + array: [BIG_INT_STRING_VALUE, 123], |
| 56 | + }, |
| 57 | + } |
| 58 | + const result = convertBigIntToString(data) |
| 59 | + expect(result).toEqual(expected) |
| 60 | + }) |
| 61 | + |
| 62 | + it("should return non-bigint values as is", () => { |
| 63 | + const result = convertBigIntToString(123) |
| 64 | + expect(result).toBe(123) |
| 65 | + }) |
| 66 | +}) |
0 commit comments