1
import { describe, expect, it } from 'vitest';
3
import { safeParseJSON } from './safeParseJSON';
5
describe('safeParseJSON', () => {
6
it('should parse a valid JSON string', () => {
7
const validJSON = '{"name": "John", "age": 30}';
8
const result = safeParseJSON(validJSON);
9
expect(result).toEqual({ name: 'John', age: 30 });
12
it('should return undefined for invalid JSON', () => {
13
const invalidJSON = '{name: John}';
14
const result = safeParseJSON(invalidJSON);
15
expect(result).toBeUndefined();
18
it('should parse an empty object', () => {
19
const emptyObject = '{}';
20
const result = safeParseJSON(emptyObject);
21
expect(result).toEqual({});
24
it('should parse an array', () => {
25
const arrayJSON = '[1, 2, 3]';
26
const result = safeParseJSON(arrayJSON);
27
expect(result).toEqual([1, 2, 3]);
30
it('should parse nested objects', () => {
31
const nestedJSON = '{"user": {"name": "John", "age": 30}}';
32
const result = safeParseJSON(nestedJSON);
33
expect(result).toEqual({ user: { name: 'John', age: 30 } });
36
it('should return undefined for an empty string', () => {
37
const result = safeParseJSON('');
38
expect(result).toBeUndefined();
41
it('should return undefined for non-string input', () => {
42
// @ts-expect-error: Testing with invalid input type
43
const result = safeParseJSON(123);
44
expect(result).toBeUndefined();
47
it('should parse JSON with special characters', () => {
48
const specialJSON = '{"message": "Hello, \\"world\\"!"}';
49
const result = safeParseJSON(specialJSON);
50
expect(result).toEqual({ message: 'Hello, "world"!' });
53
it('should parse large JSON without throwing an error', () => {
54
const largeJSON = JSON.stringify({ data: Array(1000).fill('test') });
55
const result = safeParseJSON(largeJSON);
56
expect(result).toHaveProperty('data');
57
expect(Array.isArray(result!.data)).toBe(true);
58
expect(result!.data).toHaveLength(1000);
61
it('should handle JSON with different data types', () => {
62
const mixedJSON = '{"string": "text", "number": 42, "boolean": true, "null": null}';
63
const result = safeParseJSON(mixedJSON);
64
expect(result).toEqual({