Mirror of https://github.com/roostorg/coop
github.com/roostorg/coop
1import {
2 camelCaseObjectKeysToSnakeCaseDeep,
3 camelToSnakeCase,
4 noPropertyValueFound,
5 safeGet,
6 snakeToCamelCase,
7} from './misc.js';
8
9describe('Misc utils', () => {
10 describe('String inflection', () => {
11 const mapping = {
12 id: 'id',
13 version: 'version',
14 name: 'name',
15 status_if_unexpired: 'statusIfUnexpired',
16 tags: 'tags',
17 max_daily_actions: 'maxDailyActions',
18 org_id: 'orgId',
19 creator_id: 'creatorId',
20 expiration_time: 'expirationTime',
21 condition_set: 'conditionSet',
22 action_ids: 'actionIds',
23 content_type_ids: 'contentTypeIds',
24 } as const;
25
26 describe('camelToSnakeCase', () => {
27 test('should work for simple fields', () => {
28 Object.values(mapping).forEach((v) => {
29 expect(mapping[camelToSnakeCase(v)]).toEqual(v);
30 });
31 });
32 });
33
34 describe('snakeToCamelCase', () => {
35 test('should work for simple fields', async () => {
36 Object.keys(mapping).forEach((k) => {
37 expect(snakeToCamelCase(k)).toEqual(
38 mapping[k as keyof typeof mapping],
39 );
40 });
41 });
42 });
43
44 describe('camelCaseObjectKeysToSnakeCaseDeep', () => {
45 test('should work for simple objects', () => {
46 const obj = {
47 fooBar: 'value',
48 nestedObj: {
49 bazQux: 'value',
50 },
51 };
52
53 const result = camelCaseObjectKeysToSnakeCaseDeep(obj);
54
55 expect(result).toEqual({
56 foo_bar: 'value',
57 nested_obj: {
58 baz_qux: 'value',
59 },
60 });
61 });
62
63 test('should work for arrays', () => {
64 const arr = [
65 { fooBar: 'value' },
66 { bazQux: { valueHello: 'value' } },
67 ] as const;
68
69 const result = camelCaseObjectKeysToSnakeCaseDeep(arr);
70
71 expect(result).toEqual([
72 { foo_bar: 'value' },
73 { baz_qux: { value_hello: 'value' } },
74 ]);
75 });
76 });
77 });
78
79 describe('safeGet', () => {
80 test('should short-circuit only on null/undefined/other primitives', () => {
81 const c = { d: undefined, e: null };
82 const a = { b: false, c };
83 const dummy = { a, x: 'string' };
84
85 expect(safeGet(dummy, ['a'])).toBe(a);
86 expect(safeGet(dummy, ['a', 'b'])).toBe(false);
87 expect(safeGet(dummy, ['x'])).toBe('string');
88
89 expect(safeGet(dummy, ['a', 'y'])).toBe(noPropertyValueFound);
90 expect(safeGet(dummy, ['a', 'b', 'x'])).toBe(noPropertyValueFound);
91 expect(safeGet(false, ['a', 'x', 'd'])).toBe(noPropertyValueFound);
92
93 expect(safeGet(dummy, ['a', 'c'])).toBe(c);
94 expect(safeGet(false, ['a', 'c', 'd', 'e'])).toBe(noPropertyValueFound);
95
96 expect(safeGet(false, ['a', 'c', 'f'])).toBe(noPropertyValueFound);
97 });
98 });
99});