-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Description
What problem does this address?
Currently the unit tests related to rendering blocks are using the edit component of the different blocks. However the blocks are rendered in the editor through the BlockEdit
component which includes a context with different properties like clientID
that could be required by other logic from the blocks.
In fact, I realised when testing the changes that will introduce this PR, that rendering blocks without a clientId
produce errors when running the unit tests, in this case the selector isBlockSelected
which is heavily used in blocks returns true
when the clientId
is undefined
.
What is your proposed solution?
My solution here is to add extra logic to the unit tests that renders blocks, first we should register the block as the editor does and then create a function that returns the BlockEdit
component that will render the block we want to test.
Here is an example:
/**
* Internal dependencies
*/
import { metadata, settings, name } from '../index';
/**
* WordPress dependencies
*/
import { BlockEdit } from '@wordpress/block-editor';
import { registerBlockType, unregisterBlockType } from '@wordpress/blocks';
const Block = ( { clientId, ...props } ) => (
<BlockEdit name={ name } clientId={ clientId || 0 } { ...props } />
);
describe( '<BLOCK_NAME> Block', () => {
beforeAll( () => {
registerBlockType( name, {
...metadata,
...settings,
} );
} );
afterAll( () => {
unregisterBlockType( name );
} );
it( 'renders without crashing', () => {
const component = renderer.create(
<Block />
);
const rendered = component.toJSON();
expect( rendered ).toBeTruthy();
} );
...
} );
As you can see, instead of rendering the Edit component of the block, we use the BlockEdit
component by passing the block's name through the name
prop and a default clientId
.