Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/utils.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,12 @@ const utils = {
* https://stackoverflow.com/a/2117523
*/
uuid4: () => {
// available in: v14.17.x+
if (crypto.randomUUID) {
return crypto.randomUUID();
}

// legacy behavior if native UUIDs aren't available
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
Expand Down
39 changes: 39 additions & 0 deletions test/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,45 @@ describe('utils', () => {
}).to.throw();
});
});

describe('uuid', () => {
describe('crypto.randomUUID', () => {
const crypto = require('crypto');
let randomUUID$;
let called;
beforeEach(() => {
// if it's available, mock it and ensure it's called
// otherwise, skip this whole operation
if (crypto.randomUUID) {
called = false;
randomUUID$ = crypto.randomUUID;
crypto.randomUUID = () => {
called = true;
return 'no, YOU you id';
};
}
});
afterEach(() => {
if (randomUUID$) {
crypto.randomUUID = randomUUID$;
}
});
it('is called if available', () => {
if (randomUUID$) {
expect(utils.uuid4()).to.equal('no, YOU you id');
expect(called).to.equal(true);
}
});
});
it('should return a well-formatted v4 UUID', () => {
expect(utils.uuid4()).to.match(
// regex from https://createuuid.com/validator/, specifically for v4
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i
);
// further test: could spy on crypto.randomUUID to ensure it's being used, if available
// whether that's useful is a race between using jest/sinon for these tests and dropping support for node < 14
});
});
});

function handleWarnings(doWithShimmedConsoleWarn, onWarn) {
Expand Down