Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TabContext] Introduced new prop to allow deterministic idPrefix #38192

Closed
wants to merge 3 commits into from

Conversation

filipomar
Copy link

@filipomar filipomar commented Jul 27, 2023

I am facing a problem on my tests, where I am not able to use snapshoting matching due to the internal id prefix used by the tab context being randomly generated:

image

So on this PR I have:

  • added a new prop to allow for a custom idPrefix
  • replaced the previous useState/useEffect for a useRef that won't cause useless re-renders

I haven't written tests for this as I want first some sort of tentative ok/feeback from the reviwers before putting the effort.

Please let me know if I should do any changes.

In case someone wants to change this behaviour right away, this is my current workaround, using jest, typescript and very brittle on purpose:

import React, { type FC, useLayoutEffect } from 'react'

import { TabContext } from '@mui/lab'

import { dependencies } from '../../../package.json'

/**
 * The tabs component as it is does not provide a constant internally used unique prefix
 * This makes it a constant, using the given parameter
 * Which then allows for snapshots to be used in testing
 */
export const TabsContextUniquePrefixFixer: FC<Readonly<{ uniquePrefixGenerator: () => number }>> = ({ uniquePrefixGenerator: uniquePrefix, children }) => {
    const supported = '^5.0.0-alpha.131'

    if (dependencies['@mui/lab'] !== supported) {
        /**
         * This check is here to make sure you don't forget to check if anything has changed making this dangerous fix obsolete
         * Please go check 'node_modules/mui-lab/src/TabContext/TabContext.js' and make sure the fix down below still applies
         */
        throw new Error(
            `The ${TabsContextUniquePrefixFixer.name} fix does not support @mui/lab '${dependencies['@mui/lab']}' version, only '${supported}', please check '${__filename}' for more tips on how to fix this`
        )
    }

    useLayoutEffect(() => {
        const originalRound = Math.round

        const randomSpy = jest.spyOn(Math, 'random')
        const roundSpy = jest.spyOn(Math, 'round').mockImplementation((...args) => {
            const lastRandomValue = randomSpy.mock.results[randomSpy.mock.results.length - 1]?.value
            /**
             * Constant comes from https://github.com/mui/material-ui/blob/e6e5012f1dc0534a19c99a8a437fba144413862e/packages/mui-lab/src/TabContext/TabContext.js#L15
             */
            const valuePossiblyPassedToRound = Number(lastRandomValue) * 1e5
            if (valuePossiblyPassedToRound === args[0]) {
                return uniquePrefix()
            }
            return originalRound.apply(Math, args)
        })

        return () => {
            roundSpy.mockClear()
            randomSpy.mockClear()
        }
    }, [])

    return <>{children}</>
}

export const example = (
    <TabsContextUniquePrefixFixer uniquePrefixGenerator={() => ++id}>
        <TabContext value="foo" />
    </TabsContextUniquePrefixFixer>
)

Replaced internal hook useState for a useRef to save on re-render
@mui-bot
Copy link

mui-bot commented Jul 27, 2023

Netlify deploy preview

https://deploy-preview-38192--material-ui.netlify.app/

Bundle size report

Details of bundle changes (Toolpad)
Details of bundle changes

Generated by 🚫 dangerJS against 34098fe

@zannager zannager added the component: tabs This is the name of the generic UI component, not the React module! label Jul 28, 2023
@zannager zannager requested a review from mnajdova July 28, 2023 09:02
Copy link
Member

@ZeeshanTamboli ZeeshanTamboli left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@filipomar Thanks for the PR. The issue is related to #32038.

The logic makes sense to me. And so, yes, you can add tests.

Could you also please fix the CI? Check out the Contributing guide for the details. Could you also check why the SSR related tests are failing?

@ZeeshanTamboli ZeeshanTamboli added the package: lab Specific to @mui/lab label Sep 8, 2023
@ZeeshanTamboli
Copy link
Member

Since there is no response and the PR is inactive I am closing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: tabs This is the name of the generic UI component, not the React module! package: lab Specific to @mui/lab
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants