From afe62323c4408a824755a39d7b971a8ae06f7199 Mon Sep 17 00:00:00 2001 From: Ali Molaei Date: Wed, 7 Aug 2024 21:17:57 +0330 Subject: [PATCH] fix: remove v4 options default assignment preventing native.randomUUID from being used (#786) * fix: remove options default assignment introduced during porting to ts, pull #763 preventing native.randomUUID being used * test: add unit test to check if native randomUUID should be used or not --- src/test/v4.test.ts | 23 ++++++++++++++++++++++- src/v4.ts | 2 -- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/test/v4.test.ts b/src/test/v4.test.ts index 36574f39..602aa782 100644 --- a/src/test/v4.test.ts +++ b/src/test/v4.test.ts @@ -1,6 +1,7 @@ import * as assert from 'assert'; -import test, { describe } from 'node:test'; +import test, { describe, mock } from 'node:test'; import v4 from '../v4.js'; +import native from '../native.js'; const randomBytesFixture = Uint8Array.of( 0x10, @@ -48,6 +49,26 @@ describe('v4', () => { assert.ok(id1 !== id2); }); + test('should uses native randomUUID() if no option is passed', () => { + mock.method(native, 'randomUUID'); + + assert.equal((native.randomUUID as any).mock.callCount(), 0); + v4(); + assert.equal((native.randomUUID as any).mock.callCount(), 1); + + mock.restoreAll(); + }); + + test('should not use native randomUUID() if an option is passed', () => { + mock.method(native, 'randomUUID'); + + assert.equal((native.randomUUID as any).mock.callCount(), 0); + v4({}); + assert.equal((native.randomUUID as any).mock.callCount(), 0); + + mock.restoreAll(); + }); + test('explicit options.random produces expected result', () => { const id = v4({ random: randomBytesFixture }); assert.strictEqual(id, '109156be-c4fb-41ea-b1b4-efe1671c5836'); diff --git a/src/v4.ts b/src/v4.ts index d1447f69..3370e554 100644 --- a/src/v4.ts +++ b/src/v4.ts @@ -6,8 +6,6 @@ import { unsafeStringify } from './stringify.js'; function v4(options?: Version4Options, buf?: undefined, offset?: number): string; function v4(options?: Version4Options, buf?: Uint8Array, offset?: number): Uint8Array; function v4(options?: Version4Options, buf?: Uint8Array, offset?: number): UUIDTypes { - options ??= {}; - if (native.randomUUID && !buf && !options) { return native.randomUUID(); }