import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from 'vitest';
import type { ComponentType } from 'react';
import type { AnyAction } from 'redux';
import { compose } from '@wordpress/compose';
import { Component, createRef, forwardRef } from '@wordpress/element';
import withSelect from '../';
import withDispatch from '../../with-dispatch';
import { createRegistry } from '../../../registry';
import { RegistryProvider } from '../../registry-provider';
import type { DataRegistry } from '../../../types';
/* eslint-disable @wordpress/wp-global-usage */
describe( 'withSelect', () => {
const initialScriptDebug = globalThis.SCRIPT_DEBUG;
beforeAll( () => {
// Do not run HOC in development mode; it will call `mapSelect` an extra time.
globalThis.SCRIPT_DEBUG = false;
} );
afterAll( () => {
globalThis.SCRIPT_DEBUG = initialScriptDebug;
} );
it( 'passes the relevant data to the component', () => {
const registry = createRegistry();
registry.registerStore( 'reactReducer', {
reducer: () => ( { reactKey: 'reactState' } ),
selectors: {
reactSelector: (
state: Record< string, string >,
key: string
) => state[ key ],
},
} );
// In normal circumstances, the fact that we have to add an arbitrary
// prefix to the variable name would be concerning, and perhaps an
// argument that we ought to expect developer to use select from the
// `@wordpress/data` export. But in-fact, this serves as a good deterrent for
// including both `withSelect` and `select` in the same scope, which
// shouldn't occur for a typical component, and if it did might wrongly
// encourage the developer to use `select` within the component itself.
const mapSelectToProps = vi.fn( ( _select, ownProps ) => ( {
data: _select( 'reactReducer' ).reactSelector( ownProps.keyName ),
} ) );
const OriginalComponent = vi.fn(
( props: { data?: string; keyName?: string } ) => (
{ props.data }
)
);
const DataBoundComponent =
withSelect( mapSelectToProps )( OriginalComponent );
render(
);
expect( mapSelectToProps ).toHaveBeenCalledTimes( 1 );
expect( OriginalComponent ).toHaveBeenCalledTimes( 1 );
// Wrapper is the enhanced component.
expect( screen.getByRole( 'status' ) ).toHaveTextContent(
'reactState'
);
} );
it( 'should rerun selection on state changes', async () => {
const user = userEvent.setup();
const registry = createRegistry();
registry.registerStore( 'counter', {
reducer: ( state = 0, action: AnyAction ) => {
if ( action.type === 'increment' ) {
return state + 1;
}
return state;
},
selectors: {
getCount: ( state: number ) => state,
},
actions: {
increment: () => ( { type: 'increment' } ),
},
} );
const mapSelectToProps = vi.fn( ( _select ) => ( {
count: _select( 'counter' ).getCount(),
} ) );
const mapDispatchToProps = vi.fn( ( _dispatch ) => ( {
increment: _dispatch( 'counter' ).increment,
} ) );
const OriginalComponent = vi.fn(
( props: { increment?: () => void; count?: number } ) => (
)
);
const DataBoundComponent = compose( [
withSelect( mapSelectToProps ),
withDispatch( mapDispatchToProps ),
] )( OriginalComponent ) as ComponentType;
render(
);
expect( OriginalComponent ).toHaveBeenCalledTimes( 1 );
expect( mapSelectToProps ).toHaveBeenCalledTimes( 1 );
expect( mapDispatchToProps ).toHaveBeenCalledTimes( 1 );
// Simulate a click on the button.
const button = screen.getByRole( 'button' );
await user.click( button );
expect( button ).toHaveTextContent( '1' );
// 1. Initial mount
// 2. When click handler is called.
expect( mapDispatchToProps ).toHaveBeenCalledTimes( 2 );
// 3 times
// - 1 on initial render
// - 1 on click triggering subscription firing.
// - 1 on rerender.
expect( mapSelectToProps ).toHaveBeenCalledTimes( 3 );
// Verifies component only renders twice.
expect( OriginalComponent ).toHaveBeenCalledTimes( 2 );
} );
describe( 'expected behaviour when dispatching actions during mount', () => {
// @todo Should we allow this behaviour? Side-effects
// on mount are discouraged in React (breaks Suspense and React Async Mode)
// leaving in place for now under the assumption there's current usage
// of withSelect in GB that expects support.
interface OriginalComponentProps {
increment: () => void;
count: number;
}
class OriginalComponent extends Component< OriginalComponentProps > {
constructor( props: OriginalComponentProps ) {
super( props );
props.increment();
}
componentDidMount() {
this.props.increment();
}
render() {
return
{ this.props.count }
;
}
}
let testRegistry: DataRegistry;
let renderSpy: ReturnType< typeof vi.spyOn >;
let mapSelectToProps: ReturnType< typeof vi.fn >;
let DataBoundComponent: ComponentType;
beforeEach( () => {
testRegistry = createRegistry();
testRegistry.registerStore( 'counter', {
reducer: ( state = 0, action: AnyAction ) => {
if ( action.type === 'increment' ) {
return state + 1;
}
return state;
},
selectors: {
getCount: ( state: number ) => state,
},
actions: {
increment: () => ( { type: 'increment' } ),
},
} );
renderSpy = vi.spyOn( OriginalComponent.prototype, 'render' );
mapSelectToProps = vi.fn( ( _select ) => ( {
count: _select( 'counter' ).getCount(),
} ) );
const mapDispatchToProps = vi.fn( ( _dispatch ) => ( {
increment: _dispatch( 'counter' ).increment,
} ) );
DataBoundComponent = compose( [
withSelect(
mapSelectToProps as unknown as Parameters<
typeof withSelect
>[ 0 ]
),
withDispatch( mapDispatchToProps ),
] )( OriginalComponent ) as ComponentType;
} );
it( 'should rerun if had dispatched action during mount', () => {
const { unmount } = render(
);
expect( screen.getByRole( 'status' ) ).toHaveTextContent( '2' );
// Expected 3 times because:
// - 1 on initial render
// - 1 on effect before subscription set.
// - 1 for the rerender because of the mapOutput change detected.
expect( mapSelectToProps ).toHaveBeenCalledTimes( 3 );
expect( renderSpy ).toHaveBeenCalledTimes( 2 );
unmount();
} );
it( 'should rerun on unmount and mount', () => {
const { unmount } = render(
);
unmount();
render(
);
expect( screen.getByRole( 'status' ) ).toHaveTextContent( '4' );
// Expected 6 times across the initial mount and remount:
// - 1 on initial render
// - 1 on effect before subscription set.
// - once for the rerender because of the mapOutput change detected.
expect( mapSelectToProps ).toHaveBeenCalledTimes( 6 );
expect( renderSpy ).toHaveBeenCalledTimes( 4 );
} );
} );
it( 'should rerun selection on props changes', () => {
const registry = createRegistry();
registry.registerStore( 'counter', {
reducer: ( state = 0, action: AnyAction ) => {
if ( action.type === 'increment' ) {
return state + 1;
}
return state;
},
selectors: {
getCount: ( state: number, offset: number ) => state + offset,
},
} );
const mapSelectToProps = vi.fn( ( _select, ownProps ) => ( {
count: _select( 'counter' ).getCount( ownProps.offset ),
} ) );
const OriginalComponent = vi.fn( ( props: { count?: number } ) => (