Created
February 22, 2024 06:22
-
-
Save shazron/d63caa0938f6f0d77bcf25328b87fe23 to your computer and use it in GitHub Desktop.
JSON.stringify / parse tests for state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let store = {} | |
/** @private */ | |
function put (key, value) { | |
store[key] = JSON.stringify(value) | |
} | |
/** @private */ | |
function get (key) { | |
const value = store[key] | |
try { | |
return JSON.parse(value) | |
} catch (e) { | |
return value | |
} | |
} | |
beforeEach(() => { | |
store = {} | |
}) | |
test('object', () => { | |
const key = 'my-key' | |
const value = { my: 12, value: true } | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('array', () => { | |
const key = 'my-key' | |
const value = ['foo', 'bar'] | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('boolean', () => { | |
const key = 'my-key' | |
put(key, true) | |
expect(get(key)).toStrictEqual(true) | |
put(key, false) | |
expect(get(key)).toStrictEqual(false) | |
}) | |
test('number', () => { | |
const key = 'my-key' | |
const value = 12 | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('string', () => { | |
const key = 'my-key' | |
const value = 'some string' | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('object as string (use JSON.stringify)', () => { | |
const key = 'my-key' | |
const value = JSON.stringify({ my: 12, value: true }) | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('invalid object as string 1 (manual)', () => { | |
const key = 'my-key' | |
const value = '{ my: 12, value: true }' | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('invalid object as string 2 (manual)', () => { | |
const key = 'my-key' | |
const value = '{ "my": 12, "value": true' | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
test('undefined', () => { | |
const key = 'my-key' | |
const value = undefined | |
put(key, value) | |
expect(get(key)).toStrictEqual(value) | |
}) | |
// anything passed to JSON.stringify (in the case of put above) | |
// it will use the .toJSON to serialize, so `get` will be that transformed value | |
test('date', () => { | |
const key = 'my-key' | |
const value = new Date() | |
put(key, value) | |
expect(get(key)).toStrictEqual(value.toJSON()) // have to do .toJSON() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment