test: add common component mock test utility

Signed-off-by: Erik Michelson <github@erik.michelson.eu>
This commit is contained in:
Erik Michelson 2023-10-01 23:49:47 +02:00
parent 865e127d16
commit f41e45fad9
No known key found for this signature in database
GPG key ID: DB99ADDDC5C0AF82
2 changed files with 24 additions and 4 deletions

View file

@ -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', () => {

View file

@ -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) => (
<span data-mock-component={name} {...props}>
{children}
</span>
)
})