File tree Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Expand file tree Collapse file tree 2 files changed +32
-0
lines changed Original file line number Diff line number Diff line change 1+ import assert from 'node:assert/strict'
2+ import { describe , test as it } from 'node:test'
3+ import { tryAsJSON } from './tryAsJSON.js'
4+
5+ void describe ( 'tryAsJSON()' , ( ) => {
6+ void it ( 'should return parsed JSON object if input is a valid JSON string' , ( ) => {
7+ const body = '{"name": "John", "age": 30}'
8+ const expected = { name : 'John' , age : 30 }
9+ const result = tryAsJSON ( body )
10+ assert . deepEqual ( result , expected )
11+ } )
12+
13+ void it ( 'should return null if input is not a string' , ( ) => {
14+ const body = 123
15+ const result = tryAsJSON ( body )
16+ assert . equal ( result , null )
17+ } )
18+
19+ void it ( 'should return null if input is an invalid JSON string' , ( ) => {
20+ const body = '{"name": "John", "age": 30' // Missing closing brace
21+ const result = tryAsJSON ( body )
22+ assert . equal ( result , null )
23+ } )
24+ } )
Original file line number Diff line number Diff line change 1+ export const tryAsJSON = ( body : unknown ) : Record < string , any > | null => {
2+ if ( typeof body !== 'string' ) return null
3+ try {
4+ return JSON . parse ( body )
5+ } catch {
6+ return null
7+ }
8+ }
You can’t perform that action at this time.
0 commit comments