import React from 'react';
import { render } from '@testing-library/react';

interface Props {
    className?: string;
    testId?: string;
}

// eslint-disable-next-line jest/no-export
export function testComponent<T>(
    Component: React.FC<Props & T>,
    defaultProps?: T,
    name?: string,
    testId?: string
) {
    const componentClassName = name ?? Component.displayName ?? Component.name;
    if (!componentClassName) throw new Error('Please specify the component class name');

    const renderComponent = (props?: Props) =>
        render(<Component {...defaultProps} {...(props as Props & T)} />);

    test('has className', () => {
        const { container } = renderComponent();
        const root = container.querySelector(`.${componentClassName}`);

        expect(root).toBeInTheDocument();
    });

    test('has testId', () => {
        const { getByTestId } = renderComponent();
        const root = getByTestId(testId ?? componentClassName);

        expect(root).toBeInTheDocument();
    });

    test('accepts "className"', () => {
        const className = 'my-class';
        const { container } = renderComponent({ className });
        const root = container.querySelector(`.${componentClassName}`);

        expect(root).toBeInTheDocument();
        expect(root).toHaveClass(className);
    });

    test('accepts "testId"', () => {
        const testId = 'test';
        const { getByTestId } = renderComponent({ testId });
        const root = getByTestId(testId);

        expect(root).toBeInTheDocument();
    });
}
