diff --git a/src/hooks/useId.ts b/src/hooks/useId.ts index d58a9588..331f3ca8 100644 --- a/src/hooks/useId.ts +++ b/src/hooks/useId.ts @@ -40,7 +40,7 @@ const useOriginId = getUseId(); export default useOriginId ? // Use React `useId` - function useId(id?: string) { + function useId(id?: string, disableTestMock?: boolean) { const reactId = useOriginId(); // Developer passed id is single source of truth @@ -48,15 +48,15 @@ export default useOriginId return id; } - // Test env always return mock id - if (process.env.NODE_ENV === 'test') { + // By default, test env always return mock id, but also allow force use id for test case which need to test id logic. + if (!disableTestMock && process.env.NODE_ENV === 'test') { return 'test-id'; } return reactId; } : // Use compatible of `useId` - function useCompatId(id?: string) { + function useCompatId(id?: string, disableTestMock?: boolean) { // Inner id for accessibility usage. Only work in client side const [innerId, setInnerId] = React.useState('ssr-id'); @@ -72,8 +72,8 @@ export default useOriginId return id; } - // Test env always return mock id - if (process.env.NODE_ENV === 'test') { + // By default, test env always return mock id, but also allow force use id for test case which need to test id logic. + if (!disableTestMock && process.env.NODE_ENV === 'test') { return 'test-id'; } diff --git a/tests/hooks-17.test.tsx b/tests/hooks-17.test.tsx index 1c84e57e..c020d86b 100644 --- a/tests/hooks-17.test.tsx +++ b/tests/hooks-17.test.tsx @@ -56,5 +56,19 @@ describe('hooks-17', () => { errorSpy.mockRestore(); process.env.NODE_ENV = originEnv; }); + + it('force use compat id in test env', () => { + const DemoForce: React.FC<{ id?: string }> = ({ id }) => { + const mergedId = useId(id, true); + return
; + }; + + resetUuid(); + const { container } = render(); + const ele = container.querySelector('.target-force'); + + expect(ele.id).toBeTruthy(); + expect(ele.id).not.toEqual('test-id'); + }); }); }); diff --git a/tests/hooks.test.tsx b/tests/hooks.test.tsx index f8004eb5..fca3ae1f 100644 --- a/tests/hooks.test.tsx +++ b/tests/hooks.test.tsx @@ -642,6 +642,18 @@ describe('hooks', () => { matchId(container, 'test-id'); }); + it('force use react useId in test env', () => { + const DemoForce: React.FC> = ({ id }) => { + const mergedId = useId(id, true); + return
; + }; + + const { container } = render(); + const ele = container.querySelector('.target-force'); + expect(ele.id).toBeTruthy(); + expect(ele.id).not.toEqual('test-id'); + }); + it('react useId', () => { const errorSpy = jest.spyOn(console, 'error'); const originEnv = process.env.NODE_ENV;