diff --git a/packages/amis-core/__tests__/renderers/wrapControl.test.tsx b/packages/amis-core/__tests__/renderers/wrapControl.test.tsx new file mode 100644 index 000000000..2fbfeebbf --- /dev/null +++ b/packages/amis-core/__tests__/renderers/wrapControl.test.tsx @@ -0,0 +1,58 @@ +/* + * @author: ranqirong + * @date: 2024-10-10 + * @description: + */ +import React from 'react'; +import {wrapControl} from '../../src/renderers/wrapControl'; +import {render, screen} from '@testing-library/react'; +import {RootStoreContext} from '../../src/WithRootStore'; +import {RendererStore} from '../../src/store/index'; +import {FormItemProps} from '../../src/renderers/Item'; + +const renderComponent = (WrappedComponent: any, props: any) => { + const store = RendererStore.create({}); + return render( + + + + ); +}; + +describe('constructor', () => { + it('如果传入有defaultProps包含name属性,则创建FormItemStore', () => { + const OriginComponent = (props: FormItemProps) => { + // 用于断言formItem已被注册 + return
{props.formItem?.storeType}
; + }; + OriginComponent.defaultProps = { + name: 'test' + }; + const WrappedComponent = wrapControl(OriginComponent as any); + + renderComponent(WrappedComponent, {$schema: {}}); + expect(screen.getByText('FormItemStore')).toBeInTheDocument(); + }); + + it('如果$schema中包含name属性,则创建FormItemStore', () => { + const OriginComponent = (props: FormItemProps) => { + // 用于断言formItem已被注册 + return
{props.formItem?.storeType}
; + }; + const WrappedComponent = wrapControl(OriginComponent as any); + + renderComponent(WrappedComponent, {$schema: {name: 'test'}}); + expect(screen.getByText('FormItemStore')).toBeInTheDocument(); + }); + + it('如果$schema和defaultProps中都不包含name属性,则不创建FormItemStore', () => { + const OriginComponent = (props: FormItemProps) => { + // 用于断言formItem已被注册 + return
{props.formItem?.storeType}
; + }; + const WrappedComponent = wrapControl(OriginComponent as any); + + renderComponent(WrappedComponent, {$schema: {}}); + expect(screen.queryByText('FormItemStore')).not.toBeInTheDocument(); + }); +}); diff --git a/packages/amis-core/src/renderers/wrapControl.tsx b/packages/amis-core/src/renderers/wrapControl.tsx index ef5ccdd1f..7dd4ef93d 100644 --- a/packages/amis-core/src/renderers/wrapControl.tsx +++ b/packages/amis-core/src/renderers/wrapControl.tsx @@ -176,7 +176,9 @@ export function wrapControl< this.validate = this.validate.bind(this); this.flushChange = this.flushChange.bind(this); this.renderChild = this.renderChild.bind(this); - let name = this.props.$schema.name; + let name = + this.props.$schema.name || + (ComposedComponent.defaultProps as Record)?.name; // 如果 name 是表达式 // 扩充 each 用法