Skip to content

Navigation Link block - add unit tests to cover complex onChange handler #31379

Closed

Description

@getdave

What problem does this address?

Currently in the core/navigation-link block we have a rather complex function which handles any change events occurring within the <LinkControl /> component.

onChange={ ( {
title: newTitle = '',
url: newURL = '',
opensInNewTab: newOpensInNewTab,
id,
kind: newKind = '',
type: newType = '',
} = {} ) =>
setAttributes( {
url: encodeURI( newURL ),
label: ( () => {
const normalizedTitle = newTitle.replace(
/http(s?):\/\//gi,
''
);
const normalizedURL = newURL.replace(
/http(s?):\/\//gi,
''
);
if (
newTitle !== '' &&
normalizedTitle !==
normalizedURL &&
label !== newTitle
) {
return escape( newTitle );
} else if ( label ) {
return label;
}
// If there's no label, add the URL.
return escape( normalizedURL );
} )(),
opensInNewTab: newOpensInNewTab,
id,
...( newKind && {
kind: newKind,
} ),
...( newType &&
newType !== 'URL' &&
newType !== 'post-format' && {
type: newType,
} ),
} )
}

This is a critical piece of code because it ultimately determines (by use of setAttributes()) the data about the block that will be saved:

  1. as serialized block HTML (post/site editor).
  2. to the database as nav_menu_item objects.

Therefore any errors or edge cases in this code will result in a broken block and/or navigation editor screen.

The code is currently pretty difficult to read and it's easy enough to introduce bugs as there is no (direct) test coverage.

Context

During dev of #31004 I discovered a bug whereby the id prop could inadvertently set to undefined if an onChange was called without the id prop being passed.

This was happening when the Opens in new tab setting control was toggled on core/navigation-link block variations that represent entities (eg: post-link variation) that need to be reference to the id of the object they represent:

Fixing this was simply a matter of only updating the id prop if the value was passed in the onChange handler and otherwise leaving it untouched. However the bug was very obscure and difficult to trace.

What is your proposed solution?

I propose we extract this onChange to a named function (perhaps mapLinkChangeToBlockAttributes?) and then export it so that it can be unit tested. Given how critical the code is it's important we don't inadvertently introduce regressions. We could cover this via e2e tests but it could be quite complex to cover all the possible scenarios.

Activity

  1. gwwar commented on May 10, 2021

    @gwwar
    Contributor

    This one should be closed by #31259

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions