Skip to content
40 changes: 40 additions & 0 deletions packages/blocks/src/api/test/registration.js
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,46 @@ describe( 'blocks', () => {
} );
} );

it( 'should default to empty object when attributes is omitted and without warning', () => {
registerBlockType( 'core/test-block-omitted-attributes', {
title: 'block title',
category: 'text',
save: noop,
} );

// Verify no warning was shown (unlike when explicitly set to null/undefined)
expect( console ).not.toHaveWarned();

const blockType = getBlockType(
'core/test-block-omitted-attributes'
);
expect( blockType.attributes ).toEqual( {} );
} );

it.each( [
[ 'undefined', undefined ],
[ 'null', null ],
] )(
'should warn and default to empty object when attributes is %s',
( _label, value ) => {
registerBlockType( 'core/test-block-null-attributes', {
title: 'block title',
category: 'text',
save: noop,
attributes: value,
} );

expect( console ).toHaveWarnedWith(
'The block "core/test-block-null-attributes" is registering attributes as `null` or `undefined`. Use an empty object (`attributes: {}`) or exclude the `attributes` key.'
);

const blockType = getBlockType(
'core/test-block-null-attributes'
);
expect( blockType.attributes ).toEqual( {} );
}
);

it( 'should default to browser-initialized global attributes', () => {
const attributes = { ok: { type: 'boolean' } };
unstable__bootstrapServerSideBlockDefinitions( {
Expand Down
13 changes: 13 additions & 0 deletions packages/blocks/src/store/process-block-type.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,19 @@ export const processBlockType =
),
};

// If the block is registering attributes as null or undefined, warn and default to empty object.
if (
! blockType.attributes ||
typeof blockType.attributes !== 'object'
) {
warning(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also include a test for this?

'The block "' +
name +
'" is registering attributes as `null` or `undefined`. Use an empty object (`attributes: {}`) or exclude the `attributes` key.'
);
blockType.attributes = {};
}

const settings = applyFilters(
'blocks.registerBlockType',
blockType,
Expand Down
Loading