Skip to content
Closed
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
12 changes: 6 additions & 6 deletions src/hooks/useId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,23 @@ 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
if (id) {
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<string>('ssr-id');

Expand All @@ -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';
}

Expand Down
14 changes: 14 additions & 0 deletions tests/hooks-17.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <div id={mergedId} className="target-force" />;
};

resetUuid();
const { container } = render(<DemoForce />);
const ele = container.querySelector('.target-force');

expect(ele.id).toBeTruthy();
expect(ele.id).not.toEqual('test-id');
});
});
});
12 changes: 12 additions & 0 deletions tests/hooks.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,18 @@ describe('hooks', () => {
matchId(container, 'test-id');
});

it('force use react useId in test env', () => {
const DemoForce: React.FC<Readonly<{ id?: string }>> = ({ id }) => {
const mergedId = useId(id, true);
return <div id={mergedId} className="target-force" />;
};

const { container } = render(<DemoForce />);
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;
Expand Down
Loading