Skip to content

Commit

Permalink
feat: Use helper for get random UUID
Browse files Browse the repository at this point in the history
We recently used the `randomUUID` method of `crypto`,
and added a special configuration for testing with `Jest`.

We should have added a BC at that time, because e2e tests of applications
can fail if they also do not have the correct Jest configuration.

I propose here a better approach,
which will avoid a BC and changes on the application side
  • Loading branch information
Merkur39 committed Mar 31, 2023
1 parent 3f1a755 commit e659a9b
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 9 deletions.
3 changes: 2 additions & 1 deletion react/CircleButton/index.jsx
Expand Up @@ -6,6 +6,7 @@ import Box from '../Box'
import IconButton from '../IconButton'
import Typography from '../Typography'
import { makeTypoColor, makeButtonShadow } from './helpers'
import { getRandomUUID } from '../helpers/getRandomUUID'

const useStyles = makeStyles(theme => ({
iconButton: {
Expand Down Expand Up @@ -42,7 +43,7 @@ const CircleButton = ({
...props
}) => {
const styles = useStyles({ active: variant === 'active', disabled })
const uuid = crypto.randomUUID()
const uuid = getRandomUUID()

if (!ariaLabel && !label) {
console.warn(`The "aria-label" or "label" property must be filled in.`)
Expand Down
3 changes: 2 additions & 1 deletion react/MuiCozyTheme/TextField/index.jsx
@@ -1,9 +1,10 @@
import React, { forwardRef } from 'react'
import MuiTextField from '@material-ui/core/TextField'
import { getRandomUUID } from '../../helpers/getRandomUUID'

const TextField = forwardRef(({ children, ...props }, ref) => {
// A11Y, https://v4.mui.com/api/text-field/#props
const uuid = crypto.randomUUID()
const uuid = getRandomUUID()

return (
<MuiTextField ref={ref} id={uuid} {...props}>
Expand Down
11 changes: 11 additions & 0 deletions react/helpers/getRandomUUID.js
@@ -0,0 +1,11 @@
/**
* Returns a random UUID
* @returns {string} a random UUID
*/
export const getRandomUUID = () => {
if (process.env.NODE_ENV === 'test') {
return 'random-uuid-for-jest'
}

return window.crypto.randomUUID()
}
9 changes: 9 additions & 0 deletions react/helpers/getRandomUUID.spec.js
@@ -0,0 +1,9 @@
import { getRandomUUID } from './getRandomUUID'

describe('getRandomUUID', () => {
it('returns a random uuid', () => {
const uuid = getRandomUUID()

expect(uuid).toBe('random-uuid-for-jest')
})
})
7 changes: 0 additions & 7 deletions test/jestsetup.js
@@ -1,16 +1,9 @@
import '@testing-library/jest-dom/extend-expect'
import { configure, mount, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import nodeCrypto from 'crypto'

configure({ adapter: new Adapter() })

Object.defineProperty(global, 'crypto', {
value: {
randomUUID: () => nodeCrypto.randomUUID()
}
})

global.mount = mount
global.shallow = shallow

Expand Down

0 comments on commit e659a9b

Please sign in to comment.