Skip to content

Commit

Permalink
add a util to provide data for unit testing
Browse files Browse the repository at this point in the history
  • Loading branch information
am1rb committed Jan 7, 2024
1 parent 820a7e3 commit 1853f8f
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions src/utils/getTestData.ts
Original file line number Diff line number Diff line change
@@ -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 extends z.ZodTypeAny> {
schema: Schema;
value: z.infer<Schema>;
failurePolicy: FailurePolicy;
}

interface TestData<Schema extends z.ZodTypeAny> {
defaultValue: z.infer<Schema> | undefined;
value: z.infer<Schema>;
storedValue: {
ok: string;
decoderIncompatible: string;
schemaIncompatible: string;
};
options: Options<Schema>;
}

const encoder = JSON.stringify;
const decoder = JSON.parse;

function createTestData<Schema extends z.ZodTypeAny>({
schema,
value,
failurePolicy,
}: TestDataOptions<Schema>): TestData<Schema> {
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,
},
},
};
}

0 comments on commit 1853f8f

Please # to comment.