Skip to content

Instantly share code, notes, and snippets.

@shazron
Created February 22, 2024 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shazron/d63caa0938f6f0d77bcf25328b87fe23 to your computer and use it in GitHub Desktop.
Save shazron/d63caa0938f6f0d77bcf25328b87fe23 to your computer and use it in GitHub Desktop.
JSON.stringify / parse tests for state
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