diff --git a/lib/util/__snapshots__/clone.spec.ts.snap b/lib/util/__snapshots__/clone.spec.ts.snap new file mode 100644 index 00000000000000..494dc851637c13 --- /dev/null +++ b/lib/util/__snapshots__/clone.spec.ts.snap @@ -0,0 +1,13 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`util/clone maintains same order: { + name: 'object', + type: 'object', + isObject: true, + } 1`] = ` +{ + "isObject": true, + "name": "object", + "type": "object", +} +`; diff --git a/lib/util/clone.spec.ts b/lib/util/clone.spec.ts index f0ba197d2da31a..6e7ade68f105f2 100644 --- a/lib/util/clone.spec.ts +++ b/lib/util/clone.spec.ts @@ -7,9 +7,18 @@ describe('util/clone', () => { isObject: true, }; + it('returns null', () => { + const res = clone(null); + expect(res).toBeNull(); + }); + it('maintains same order', () => { const res = clone(obj); - expect(Object.keys(res)).toEqual(Object.keys(obj)); + expect(res).toMatchSnapshot(`{ + name: 'object', + type: 'object', + isObject: true, + }`); }); it('assigns "[Circular]" to circular references', () => { diff --git a/lib/util/clone.ts b/lib/util/clone.ts index c1cee1716f5ef5..67813c024241fd 100644 --- a/lib/util/clone.ts +++ b/lib/util/clone.ts @@ -1,5 +1,6 @@ import { quickStringify } from './stringify'; export function clone(input: T | null = null): T { - return JSON.parse(quickStringify(input)); + const stringifiedInput = quickStringify(input); + return stringifiedInput ? JSON.parse(stringifiedInput) : null; } diff --git a/lib/util/fingerprint.spec.ts b/lib/util/fingerprint.spec.ts new file mode 100644 index 00000000000000..64f9ae48a0bc3b --- /dev/null +++ b/lib/util/fingerprint.spec.ts @@ -0,0 +1,27 @@ +import { fingerprint } from './fingerprint'; + +describe('util/fingerprint', () => { + const obj: any = { + name: 'object', + type: 'object', + isObject: true, + }; + + const obj2: any = { + type: 'object', + name: 'object', + isObject: true, + }; + + it('returns empty string', () => { + const res = fingerprint(undefined); + expect(res).toBeEmptyString(); + }); + + it('maintains deterministic order', () => { + const res = fingerprint(obj); + const res2 = fingerprint(obj2); + expect(res).not.toEqual(JSON.stringify(obj)); // shows that safeStringify changes the original order + expect(res).toEqual(res2); + }); +}); diff --git a/lib/util/fingerprint.ts b/lib/util/fingerprint.ts index 9704e77031b313..d4c009b93e5b58 100644 --- a/lib/util/fingerprint.ts +++ b/lib/util/fingerprint.ts @@ -2,5 +2,6 @@ import hasha from 'hasha'; import { safeStringify } from './stringify'; export function fingerprint(input: unknown): string { - return hasha(safeStringify(input)); + const stringifiedInput = safeStringify(input); + return stringifiedInput ? hasha(stringifiedInput) : ''; }