From f41e45fad950fee3732ada18d90ddb6dcd7c7827 Mon Sep 17 00:00:00 2001 From: Erik Michelson Date: Sun, 1 Oct 2023 23:49:47 +0200 Subject: [PATCH] test: add common component mock test utility Signed-off-by: Erik Michelson --- .../application-error-alert.spec.tsx | 5 +--- frontend/src/test-utils/mock-component.tsx | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 frontend/src/test-utils/mock-component.tsx diff --git a/frontend/src/components/common/application-error-alert/application-error-alert.spec.tsx b/frontend/src/components/common/application-error-alert/application-error-alert.spec.tsx index d5a3fe40f..1f52e20cc 100644 --- a/frontend/src/components/common/application-error-alert/application-error-alert.spec.tsx +++ b/frontend/src/components/common/application-error-alert/application-error-alert.spec.tsx @@ -6,11 +6,8 @@ import { render } from '@testing-library/react' import { ApplicationErrorAlert } from './application-error-alert' -import type { AlertIconProps } from './alert-icon' -jest.mock('./alert-icon', () => ({ - AlertIcon: (props: AlertIconProps) => `This is a mock for "AlertIcon". Props: ${JSON.stringify(props)}` -})) +jest.mock('./alert-icon', () => require('../../../test-utils/mock-component').mockComponent('AlertIcon')) describe('ApplicationErrorAlert', () => { it('renders correctly', () => { diff --git a/frontend/src/test-utils/mock-component.tsx b/frontend/src/test-utils/mock-component.tsx new file mode 100644 index 000000000..c404c9711 --- /dev/null +++ b/frontend/src/test-utils/mock-component.tsx @@ -0,0 +1,23 @@ +/* + * SPDX-FileCopyrightText: 2023 The HedgeDoc developers (see AUTHORS file) + * + * SPDX-License-Identifier: AGPL-3.0-only + */ +import React from 'react' + +/** + * Provides a factory function for jest.mock to mock a React functional component. + * The component will be rendered as a span with a data-mock-component attribute + * containing the name of the component as well as all props and children passed to it. + * + * @param name The name of the component to mock. + * @return An object that contains the mocked component. + */ +export const mockComponent = (name: string) => ({ + // eslint-disable-next-line react/display-name + [name]: ({ children, ...props }: React.PropsWithChildren) => ( + + {children} + + ) +})