/* eslint-disable import/prefer-default-export */ import { act } from '@testing-library/react'; import React from 'react'; import MediaLibraryModal from '@staticcms/core/components/media-library/MediaLibraryModal'; import { store } from '@staticcms/core/store'; import { createMockWidgetControlProps } from '@staticcms/test/data/widgets.mock'; import { renderWithProviders } from '@staticcms/test/test-utils'; import type { BaseField, ObjectValue, UnknownField, WidgetControlProps } from '@staticcms/core'; import type { FC } from 'react'; export interface WidgetControlHarnessOptions { useFakeTimers?: boolean; withMediaLibrary?: boolean; } export type WidgetControlHarnessParams = Parameters< typeof createMockWidgetControlProps >[0]; export type WidgetControlHarnessProps = Omit< WidgetControlHarnessParams, 'field' > & Pick>, 'field'>; export interface WidgetControlHarnessReturn extends Omit, 'rerender'> { rerender: (rerenderProps?: Omit, 'field'> | undefined) => { props: Omit, 'field'> | undefined; }; store: typeof store; props: WidgetControlProps; } export type WidgetControlHarness = ( renderProps?: WidgetControlHarnessProps, renderOptions?: WidgetControlHarnessOptions, ) => WidgetControlHarnessReturn; export const createWidgetControlHarness = ( Component: FC>, defaults: Omit>, 'field'> & Pick, 'field'>, options?: WidgetControlHarnessOptions, ): WidgetControlHarness => { return ( renderProps?: WidgetControlHarnessProps, renderOptions?: WidgetControlHarnessOptions, ) => { const { useFakeTimers = false, withMediaLibrary = false } = renderOptions ?? options ?? {}; if (useFakeTimers) { jest.useFakeTimers({ now: new Date(2023, 1, 12, 10, 15, 35, 0) }); } else { jest.useRealTimers(); } const field = renderProps?.field ?? defaults.field; const props = createMockWidgetControlProps({ ...defaults, ...renderProps, field }); const result = renderWithProviders( <> {withMediaLibrary ? : null} , ); if (useFakeTimers) { act(() => { jest.advanceTimersByTime(1000); }); } const rerender = (rerenderProps?: Omit, 'field'>) => { const finalRerenderProps = { ...props, ...rerenderProps, } as WidgetControlProps; result.rerender( <> {withMediaLibrary ? : null} , ); return { props: rerenderProps }; }; return { ...result, props, rerender, store }; }; };