diff --git a/src/ErrorMessage.test.tsx b/src/ErrorMessage.test.tsx index 4c8636b..738ff6f 100644 --- a/src/ErrorMessage.test.tsx +++ b/src/ErrorMessage.test.tsx @@ -3,6 +3,26 @@ import { render } from '@testing-library/react'; import { ErrorMessage } from './ErrorMessage'; describe('ErrorMessage', () => { + it.each([ + 'span' as const, + ({ children }: { children: React.ReactNode }) => ( + {children} + ), + ])('uses as before render for %s', (as) => { + const renderMessage = jest.fn(() => wrong renderer); + const { container } = render( + , + ); + expect(container.textContent).toBe('Required'); + expect(container.querySelector('span, strong')).not.toBeNull(); + expect(renderMessage).not.toHaveBeenCalled(); + }); + it('should render correctly', () => { const { asFragment } = render(); diff --git a/src/ErrorMessage.tsx b/src/ErrorMessage.tsx index 0196985..80b4e6e 100644 --- a/src/ErrorMessage.tsx +++ b/src/ErrorMessage.tsx @@ -31,12 +31,17 @@ const ErrorMessage = < return React.isValidElement(as) ? React.cloneElement(as, props) + : as + ? React.createElement( + as as React.ComponentType | keyof JSX.IntrinsicElements, + props, + ) : render ? (render({ message: messageFromRegister || message, messages: types, }) as React.ReactElement) - : React.createElement((as as string) || React.Fragment, props); + : React.createElement(React.Fragment, props); }; export { ErrorMessage }; diff --git a/src/__snapshots__/ErrorMessage.test.tsx.snap b/src/__snapshots__/ErrorMessage.test.tsx.snap index f9fc891..82df838 100644 --- a/src/__snapshots__/ErrorMessage.test.tsx.snap +++ b/src/__snapshots__/ErrorMessage.test.tsx.snap @@ -18,7 +18,9 @@ exports[`ErrorMessage should render correctly with flat errors and as with compo exports[`ErrorMessage should render correctly with flat errors and as with component and render 1`] = ` - flat +
+ flat +
`;