Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created August 30, 2021 16:06
Show Gist options
  • Save sibelius/cee85875995ffc73908752bada89f070 to your computer and use it in GitHub Desktop.
Save sibelius/cee85875995ffc73908752bada89f070 to your computer and use it in GitHub Desktop.
mock uuid v4 unique and stable for tests
jest.mock('uuid', () => {
const base = '9134e286-6f71-427a-bf00-';
let current = 100000000000;
return {
v4: () => {
const uuid = base + current.toString();
current++;
return uuid;
}
}
});
@sibelius
Copy link
Author

const base = '9134e286-6f71-427a-bf00-';
let current = 100000000000;

const v4 = jest.fn(() => {
  const uuid = base + current.toString();
  current++;

  return uuid;
});

// TODO - be able to reset uuid mock

export { v4 };

@sibelius
Copy link
Author

import { v4 as uuidv4 } from 'uuid';

beforeEach(async () => {
  jest.clearAllMocks();
});

it('v1', async () => {
  const uuid = uuidv4();

  expect(uuid).toBe('9134e286-6f71-427a-bf00-100000000000');

  const uuid2 = uuidv4();

  expect(uuid2).toBe('9134e286-6f71-427a-bf00-100000000001');
});

it('v2', async () => {
  const uuid = uuidv4();

  expect(uuid).toBe('9134e286-6f71-427a-bf00-100000000000');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment