import * as React from 'react'; import { HocBaseComponents } from '..'; import { render, waitFor } from '@testing-library/react'; describe('plugin test', () => { it('用户传入 ref,插件不修改 ref', async () => { // 组件实现 const BaseComponent = React.forwardRef< { getName: () => string; }, { name: string; } >((props, ref) => { React.useImperativeHandle(ref, () => { return { getName() { return props.name; }, }; }, [props.name]); return
base component,my name = {props.name}
; }); BaseComponent.displayName = 'BaseComponent'; // 生成 ref const ref = { current: null, }; const plugins = [ (props) => { return { props: { ...props, }, }; }, ]; const BaseComponentWithPlugin = React.forwardRef< { getName: () => string; }, { name: string; } >((props, upperRef) => { // 这个 console.log 只是为了 props.name 被引用到 console.log(props.name); return HocBaseComponents(BaseComponent, { props, plugins, ref: upperRef, }); }); BaseComponentWithPlugin.displayName = 'BaseComponentWithPlugin'; const { getByText } = render( , ); await waitFor(() => getByText('base component,my name = base')); expect(ref.current.getName()).toBe('base'); }); it('用户不传 ref, 插件覆盖', async () => { const BaseComponent = React.forwardRef< { getName: () => string; }, { name: string; } >((props, ref) => { React.useImperativeHandle(ref, () => { return { getName() { return props.name; }, }; }, [props.name]); return
base component,my name = {props.name}
; }); BaseComponent.displayName = 'BaseComponent'; // Add display name const ref = { current: null, }; const plugins = [ (props) => { return { props: { ...props, name: 'plugin1', ref, }, }; }, (props) => { return { props: { ...props, name: 'plugin2', }, }; }, ]; const BaseComponentWithPlugin = (props) => { return HocBaseComponents(BaseComponent, { props, plugins, }); }; const { getByText } = render(); await waitFor(() => getByText('base component,my name = plugin2')); expect(ref.current.getName()).toBe('plugin2'); }); });