diff --git a/src/utils/getTestData.ts b/src/utils/getTestData.ts new file mode 100644 index 0000000..35e1d01 --- /dev/null +++ b/src/utils/getTestData.ts @@ -0,0 +1,78 @@ +import { z } from 'zod'; +import { Options } from '../types/Options'; +import { FailurePolicy } from '../types/FailurePolicy'; +import { getDefaultValue } from './getDefaultValue'; + +export const SAMPLE_KEY = 'sample-key'; + +export function getTestData({ + withDefaultValue = false, + failurePolicy = 'exception', +}: { + withDefaultValue?: boolean; + failurePolicy?: FailurePolicy; +} = {}) { + const schema = z.object({ id: z.number(), label: z.string() }); + const schemaWithDefault = schema.default({ id: 1, label: 'default value' }); + + return createTestData({ + schema: withDefaultValue ? schemaWithDefault : schema, + value: { id: 99, label: 'data in storage' }, + failurePolicy, + }); +} + +interface TestDataOptions { + schema: Schema; + value: z.infer; + failurePolicy: FailurePolicy; +} + +interface TestData { + defaultValue: z.infer | undefined; + value: z.infer; + storedValue: { + ok: string; + decoderIncompatible: string; + schemaIncompatible: string; + }; + options: Options; +} + +const encoder = JSON.stringify; +const decoder = JSON.parse; + +function createTestData({ + schema, + value, + failurePolicy, +}: TestDataOptions): TestData { + return { + defaultValue: getDefaultValue(schema), + value, + storedValue: { + ok: encoder(value), + decoderIncompatible: 'something incompatible with what decoder expects', + schemaIncompatible: encoder(true), + }, + options: { + decoder, + encoder, + schema, + transformDecodedValue: value => value, + storage: { + getItem: jest.fn(), + setItem: jest.fn(), + removeItem: jest.fn(), + }, + logger: { + error: jest.fn(), + }, + failurePolicy: { + decodeError: failurePolicy, + encodeError: failurePolicy, + schemaCheck: failurePolicy, + }, + }, + }; +}