Commit 1afc9b84018 for woocommerce
commit 1afc9b84018da44e48774330b588e600469b848f
Author: Filipe Varela <filipe@automattic.com>
Date: Wed Dec 2 03:49:15 2026 +0000
Fix misleading error copy on the admin NoMatch screen (#67779)
* Fix misleading error copy on the admin NoMatch screen
This screen renders whenever no registered page matches the current path
- a typo in the ?path= query arg, or a JS chunk that 404s - but the copy
said "Sorry, you are not allowed to access this page," which points at a
permissions problem that isn't there. Anyone hitting it goes looking at
capabilities and access control instead of the URL.
Rewrite the message to name the actual cause and give a next step, and
change the "Not allowed" breadcrumb to match, since it carried the same
wrong framing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Add changelog entry for NoMatch error copy fix
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Split the NoMatch screen into "not found" and "access denied"
Per @chihsuan's review: the previous copy assumed every path landing on
this screen was simply unmatched, but pages the current user lacks the
capability for are also dropped from the route list before this screen
ever renders, on a stock install. Those users were told to check for a
typo and go to Home, which they can't open either.
Tell the two apart by checking the full, unfiltered page list against
the requested path - if it matches a real page the user just doesn't
have the capability for, show "Access denied" with a next step instead.
The breadcrumb (which doubles as the page's own <h1>) needed the same
fix, since it's evaluated outside a component and can't use hooks; added
a plain, non-hook capability check for that context and share it with
the card content so the two can't disagree.
Note that this can only really be observed as a non-administrator: on a
single-site install, is_super_admin short-circuits capability checks for
admins, matching how the rest of the app's own capability check already
worked before this change.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Drop the redundant heading from the NoMatch card
The card's own heading always said exactly what the page title above it
already said, so the two just echoed each other. Keep the card to its
body copy and let the page title carry the heading on its own.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Address review feedback on the NoMatch screen
- Read pages with getPages() instead of usePages(), so unmounting NoMatch
no longer removes the layout's listener for late-registered pages.
- Drop the "return to WooCommerce Home" hint, since users without
manage_woocommerce can't open Home.
- Mark the path param as optional to fix the type check.
- Cover the "Access denied" case in the changelog entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Decide access denied in the layout instead of the NoMatch screen
_Layout now renders pages the current user can't open as access-denied
routes instead of dropping them, so the message shows right away rather
than after the 3-second "not found" delay. This removes the copied
capability check and path matching from controller.js, and the
catch-all route goes back to always meaning "Page not found".
Also moves the NoMatch card to the @wordpress/ui Card and fixes the
Prettier indentation that was failing lint.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep pages loading until the user resolves and match routes by shape
While the current user is still loading, pages that need a capability
now keep a loading route instead of falling through to the catch-all,
which would say "Page not found" after 3 seconds.
An open page now also wins over a denied page whose pattern differs
only by parameter names (`/x/:id` vs `/x/:slug`). React Router breaks
ties by registration order, so the denied route could match first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Wait for a resolved user before checking page capabilities
core-data's current user is `{}` until it resolves, not undefined. So
_Layout's `! user` check skipped the loading route, and
useUser().currentUserCan() threw reading `{}.capabilities[capability]`.
currentUserCan() now returns false when the user or their capabilities
are missing, and _Layout only treats the user as resolved once the
record has an id. Until then, capability-gated pages show the loading
spinner.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Fix Prettier indentation in NoMatch.tsx
* Type page containers as components and drop the NoMatch timer guard
* Trim test comments that repeat the test names
* Remove the unused NoMatch.tsx ESLint suppression
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Chi-Hsuan Huang <chihsuan.tw@gmail.com>
diff --git a/packages/js/data/changelog/fix-50552-current-user-can-unresolved b/packages/js/data/changelog/fix-50552-current-user-can-unresolved
new file mode 100644
index 00000000000..e89515558ba
--- /dev/null
+++ b/packages/js/data/changelog/fix-50552-current-user-can-unresolved
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Return false from `useUser().currentUserCan()` instead of throwing when the current user has not loaded yet.
diff --git a/packages/js/data/src/user/test/use-user.ts b/packages/js/data/src/user/test/use-user.ts
new file mode 100644
index 00000000000..9607502d20b
--- /dev/null
+++ b/packages/js/data/src/user/test/use-user.ts
@@ -0,0 +1,71 @@
+/**
+ * External dependencies
+ */
+import { renderHook } from '@testing-library/react';
+
+/**
+ * Internal dependencies
+ */
+import { useUser } from '../use-user';
+
+const mockGetCurrentUser = jest.fn();
+
+jest.mock( '@wordpress/data', () => ( {
+ ...jest.requireActual( '@wordpress/data' ),
+ useSelect: ( callback: ( select: () => unknown ) => unknown ) =>
+ callback( () => ( {
+ getCurrentUser: mockGetCurrentUser,
+ hasStartedResolution: jest.fn().mockReturnValue( true ),
+ hasFinishedResolution: jest.fn().mockReturnValue( false ),
+ } ) ),
+} ) );
+
+describe( 'useUser() hook', () => {
+ describe( 'currentUserCan', () => {
+ it( 'returns false without throwing while the current user is an unresolved empty record', () => {
+ mockGetCurrentUser.mockReturnValue( {} );
+ const { result } = renderHook( () => useUser() );
+
+ expect(
+ result.current.currentUserCan( 'manage_woocommerce' )
+ ).toBe( false );
+ } );
+
+ it( 'returns false when the current user is undefined', () => {
+ mockGetCurrentUser.mockReturnValue( undefined );
+ const { result } = renderHook( () => useUser() );
+
+ expect(
+ result.current.currentUserCan( 'manage_woocommerce' )
+ ).toBe( false );
+ } );
+
+ it( 'returns whether the current user has the capability', () => {
+ mockGetCurrentUser.mockReturnValue( {
+ id: 1,
+ is_super_admin: false,
+ capabilities: { manage_woocommerce: true },
+ } );
+ const { result } = renderHook( () => useUser() );
+
+ expect(
+ result.current.currentUserCan( 'manage_woocommerce' )
+ ).toBe( true );
+ expect( result.current.currentUserCan( 'manage_options' ) ).toBe(
+ false
+ );
+ } );
+
+ it( 'returns true for a super admin', () => {
+ mockGetCurrentUser.mockReturnValue( {
+ id: 1,
+ is_super_admin: true,
+ } );
+ const { result } = renderHook( () => useUser() );
+
+ expect( result.current.currentUserCan( 'manage_options' ) ).toBe(
+ true
+ );
+ } );
+ } );
+} );
diff --git a/packages/js/data/src/user/use-user.ts b/packages/js/data/src/user/use-user.ts
index 3b23d2e68c9..63f2c1ec86f 100644
--- a/packages/js/data/src/user/use-user.ts
+++ b/packages/js/data/src/user/use-user.ts
@@ -32,15 +32,13 @@ export const useUser = () => {
}, [] );
const currentUserCan = ( capability: string ) => {
- if ( userData.user && userData.user.is_super_admin ) {
+ if ( userData.user?.is_super_admin ) {
return true;
}
- if ( userData.user && userData.user.capabilities[ capability ] ) {
- return true;
- }
-
- return false;
+ // Before it resolves, core-data's current user is `{}`, with no
+ // capabilities to read.
+ return Boolean( userData.user?.capabilities?.[ capability ] );
};
return {
diff --git a/plugins/woocommerce/changelog/fix-50552-nomatch-error-copy b/plugins/woocommerce/changelog/fix-50552-nomatch-error-copy
new file mode 100644
index 00000000000..02e2ce37830
--- /dev/null
+++ b/plugins/woocommerce/changelog/fix-50552-nomatch-error-copy
@@ -0,0 +1,4 @@
+Significance: patch
+Type: fix
+
+Show "Page not found" or "Access denied" in WooCommerce admin instead of a misleading "not allowed" error.
diff --git a/plugins/woocommerce/client/admin/client/layout/NoMatch.tsx b/plugins/woocommerce/client/admin/client/layout/NoMatch.tsx
index cef6d29bd2a..23971d0f530 100644
--- a/plugins/woocommerce/client/admin/client/layout/NoMatch.tsx
+++ b/plugins/woocommerce/client/admin/client/layout/NoMatch.tsx
@@ -7,13 +7,30 @@ import { useState, useEffect } from '@wordpress/element';
* External dependencies
*/
import { __ } from '@wordpress/i18n';
-import { Card, CardBody } from '@wordpress/components';
+import { Card } from '@wordpress/ui';
import { Spinner } from '@woocommerce/components';
import { Text } from '@woocommerce/experimental';
import { WooHeaderPageTitle } from '@woocommerce/admin-layout';
-const NoMatch = () => {
- const [ isDelaying, setIsDelaying ] = useState( true );
+type NoMatchReason = 'not-found' | 'access-denied';
+
+const Loading = () => (
+ <>
+ <WooHeaderPageTitle>
+ { __( 'Loading…', 'woocommerce' ) }
+ </WooHeaderPageTitle>
+ <div className="woocommerce-layout__loading">
+ <Spinner />
+ </div>
+ </>
+);
+
+const NoMatch = ( { reason = 'not-found' }: { reason?: NoMatchReason } ) => {
+ // A denied page is already known to exist, so there is nothing to wait
+ // for and the message can show right away.
+ const [ isDelaying, setIsDelaying ] = useState(
+ reason !== 'access-denied'
+ );
/*
* Delay for 3 seconds to wait if there are routing pages added after the
@@ -31,32 +48,42 @@ const NoMatch = () => {
}, [] );
if ( isDelaying ) {
- return (
- <>
- <WooHeaderPageTitle>
- { __( 'Loading…', 'woocommerce' ) }
- </WooHeaderPageTitle>
- <div className="woocommerce-layout__loading">
- <Spinner />
- </div>
- </>
- );
+ return <Loading />;
}
+ const message =
+ reason === 'access-denied'
+ ? __(
+ 'You do not have permission to view this page. Ask a site administrator for help.',
+ 'woocommerce'
+ )
+ : __(
+ 'We couldn’t find that page. Check the address for a typo.',
+ 'woocommerce'
+ );
+
return (
<div className="woocommerce-layout__no-match">
- <Card>
- <CardBody>
- <Text>
- { __(
- 'Sorry, you are not allowed to access this page.',
- 'woocommerce'
- ) }
- </Text>
- </CardBody>
- </Card>
+ <Card.Root className="woocommerce-layout__no-match-card">
+ <Card.Content>
+ <Text>{ message }</Text>
+ </Card.Content>
+ </Card.Root>
</div>
);
};
-export { NoMatch };
+/**
+ * Shown in place of a registered page the current user lacks the
+ * capability to view.
+ */
+const AccessDenied = () => <NoMatch reason="access-denied" />;
+
+/**
+ * Shown in place of a registered page while the current user is still
+ * loading, so the page waits for their capabilities instead of falling
+ * through to "not found".
+ */
+const CheckingAccess = Loading;
+
+export { NoMatch, AccessDenied, CheckingAccess };
diff --git a/plugins/woocommerce/client/admin/client/layout/controller.js b/plugins/woocommerce/client/admin/client/layout/controller.js
index 8b3495bf276..3a64a49aec8 100644
--- a/plugins/woocommerce/client/admin/client/layout/controller.js
+++ b/plugins/woocommerce/client/admin/client/layout/controller.js
@@ -331,7 +331,7 @@ export const getPages = ( reports = [] ) => {
path: '*',
breadcrumbs: [
...initialBreadcrumbs,
- __( 'Not allowed', 'woocommerce' ),
+ __( 'Page not found', 'woocommerce' ),
],
wpOpenMenu: 'toplevel_page_woocommerce',
} );
diff --git a/plugins/woocommerce/client/admin/client/layout/hooks/use-page-classes.ts b/plugins/woocommerce/client/admin/client/layout/hooks/use-page-classes.ts
index e70eeab24b9..732aac67eb6 100644
--- a/plugins/woocommerce/client/admin/client/layout/hooks/use-page-classes.ts
+++ b/plugins/woocommerce/client/admin/client/layout/hooks/use-page-classes.ts
@@ -1,11 +1,12 @@
/**
* External dependencies
*/
+import type { ComponentType } from 'react';
import { useEffect } from '@wordpress/element';
import { Params } from 'react-router-dom';
export type Page = {
- container?: JSX.Element;
+ container?: ComponentType< Record< string, unknown > >;
path?: string;
breadcrumbs:
| string[]
diff --git a/plugins/woocommerce/client/admin/client/layout/index.tsx b/plugins/woocommerce/client/admin/client/layout/index.tsx
index c54bd1ddba9..71f18f3a03f 100644
--- a/plugins/woocommerce/client/admin/client/layout/index.tsx
+++ b/plugins/woocommerce/client/admin/client/layout/index.tsx
@@ -3,6 +3,7 @@
*/
import { compose } from '@wordpress/compose';
import { useSelect } from '@wordpress/data';
+import { __ } from '@wordpress/i18n';
import {
unstable_HistoryRouter as HistoryRouter,
type HistoryRouterProps,
@@ -52,6 +53,7 @@ import { Header } from '../header';
import { Footer } from './footer';
import { TransientNotices } from './transient-notices';
import { usePageClasses, Page } from './hooks/use-page-classes';
+import { AccessDenied, CheckingAccess } from './NoMatch';
import MarketplaceBanner from '../marketplace/components/banner/banner';
const BaseLayout = ( { page }: { page: Page } ) => {
@@ -186,10 +188,77 @@ const BaseLayout = ( { page }: { page: Page } ) => {
);
};
+/**
+ * Stands in for a registered page the current user can't open (yet), so they
+ * aren't sent to the catch-all "not found" route.
+ *
+ * @param page The page the user can't open.
+ * @param container What to show in its place.
+ * @param title The breadcrumb title.
+ */
+const getStandInPage = (
+ page: Page,
+ container: Page[ 'container' ],
+ title: string
+): Page => ( {
+ path: page.path,
+ container,
+ breadcrumbs: [ getAdminSetting( 'woocommerceTranslation' ), title ],
+ wpOpenMenu: 'toplevel_page_woocommerce',
+} );
+
+/**
+ * Reduces a route pattern to its shape, so patterns that differ only by
+ * parameter names (`/x/:id` and `/x/:slug`) count as the same route.
+ *
+ * @param path The route pattern.
+ */
+const getPatternShape = ( path = '' ) => path.replace( /:[\w-]+/g, ':' );
+
export const _Layout = () => {
- const { currentUserCan } = useUser();
+ const { currentUserCan, user } = useUser();
const pages = usePages() as Page[];
+ // Before it resolves, core-data's current user is `{}` rather than
+ // undefined, so check for a real user record.
+ const isUserResolved = Boolean( user?.id );
+ const canOpen = ( page: Page ) =>
+ ! page.capability ||
+ ( isUserResolved && currentUserCan( page.capability ) );
+ const openShapes = new Set(
+ pages.filter( canOpen ).map( ( page ) => getPatternShape( page.path ) )
+ );
+ const routes = pages.flatMap( ( page ) => {
+ if ( canOpen( page ) ) {
+ return [ page ];
+ }
+
+ // A page the user can open owns this route, so let it match.
+ if ( openShapes.has( getPatternShape( page.path ) ) ) {
+ return [];
+ }
+
+ // Until the user loads, their capabilities are unknown: wait rather
+ // than deny access or fall through to "not found".
+ if ( ! isUserResolved ) {
+ return [
+ getStandInPage(
+ page,
+ CheckingAccess,
+ __( 'Loading…', 'woocommerce' )
+ ),
+ ];
+ }
+
+ return [
+ getStandInPage(
+ page,
+ AccessDenied,
+ __( 'Access denied', 'woocommerce' )
+ ),
+ ];
+ } );
+
// get the basename, usually 'wp-admin/' but can be something else if the site installation changed it
const path = document.location.pathname;
const basename = path.substring( 0, path.lastIndexOf( '/' ) );
@@ -205,23 +274,17 @@ export const _Layout = () => {
>
{ /* @ts-expect-error basename is not typed */ }
<Routes basename={ basename }>
- { pages
- .filter(
- ( page ) =>
- ! page.capability ||
- currentUserCan( page.capability )
- )
- .map( ( page ) => {
- return (
- <Route
- key={ page.path }
- path={ page.path || '' }
- // @ts-expect-error react-router-dom v6 dropped the `exact` prop; kept here for runtime compatibility.
- exact
- element={ <BaseLayout page={ page } /> }
- />
- );
- } ) }
+ { routes.map( ( page ) => {
+ return (
+ <Route
+ key={ page.path }
+ path={ page.path || '' }
+ // @ts-expect-error react-router-dom v6 dropped the `exact` prop; kept here for runtime compatibility.
+ exact
+ element={ <BaseLayout page={ page } /> }
+ />
+ );
+ } ) }
</Routes>
</HistoryRouter>
);
diff --git a/plugins/woocommerce/client/admin/client/layout/style.scss b/plugins/woocommerce/client/admin/client/layout/style.scss
index 0b07a92e0a4..6be72ce2d08 100644
--- a/plugins/woocommerce/client/admin/client/layout/style.scss
+++ b/plugins/woocommerce/client/admin/client/layout/style.scss
@@ -19,7 +19,7 @@
align-items: center;
justify-content: center;
- .components-card {
+ .woocommerce-layout__no-match-card {
max-width: 680px;
width: 100%;
}
diff --git a/plugins/woocommerce/client/admin/client/layout/test/index.test.js b/plugins/woocommerce/client/admin/client/layout/test/index.test.js
index f2d408b9313..39f4cf4e076 100644
--- a/plugins/woocommerce/client/admin/client/layout/test/index.test.js
+++ b/plugins/woocommerce/client/admin/client/layout/test/index.test.js
@@ -11,33 +11,41 @@ import * as navigation from '@woocommerce/navigation';
*/
import { PAGES_FILTER } from '../controller';
import { _Layout as Layout } from '../index';
+import { NoMatch } from '../NoMatch';
-jest.mock( '@wordpress/data', () => ( {
- ...jest.requireActual( '@wordpress/data' ),
- useSelect: jest.fn().mockImplementation( ( callback ) => {
- const selector = {
- getActivePlugins: jest.fn().mockReturnValue( [] ),
- isJetpackConnected: jest.fn().mockReturnValue( false ),
- getInstalledPlugins: jest.fn().mockReturnValue( [] ),
- isResolving: jest.fn().mockReturnValue( false ),
- hasFinishedResolution: jest.fn().mockReturnValue( true ),
- getCurrentUser: jest.fn().mockReturnValue( {
- currentUserCan: jest.fn().mockReturnValue( true ),
- } ),
- getOption: jest.fn().mockReturnValue( 'wc-admin' ),
- getNotices: jest.fn().mockReturnValue( [] ),
- getNotes: jest.fn().mockReturnValue( [] ),
- hasStartedResolution: jest.fn().mockReturnValue( true ),
- };
- return callback( () => selector );
- } ),
-} ) );
+// Backs useUser(), which _Layout uses to decide which pages the current user
+// can open.
+const mockedGetCurrentUser = jest.fn().mockReturnValue( {
+ id: 1,
+ is_super_admin: true,
+} );
+
+jest.mock( '@wordpress/data', () => {
+ const actual = jest.requireActual( '@wordpress/data' );
+ return {
+ ...actual,
+ useSelect: jest.fn().mockImplementation( ( callback ) => {
+ const selector = {
+ getActivePlugins: jest.fn().mockReturnValue( [] ),
+ isJetpackConnected: jest.fn().mockReturnValue( false ),
+ getInstalledPlugins: jest.fn().mockReturnValue( [] ),
+ isResolving: jest.fn().mockReturnValue( false ),
+ hasFinishedResolution: jest.fn().mockReturnValue( true ),
+ getCurrentUser: ( ...args ) => mockedGetCurrentUser( ...args ),
+ getOption: jest.fn().mockReturnValue( 'wc-admin' ),
+ getNotices: jest.fn().mockReturnValue( [] ),
+ getNotes: jest.fn().mockReturnValue( [] ),
+ hasStartedResolution: jest.fn().mockReturnValue( true ),
+ };
+ return callback( () => selector );
+ } ),
+ };
+} );
jest.mock( '@woocommerce/data', () => {
const originalModule = jest.requireActual( '@woocommerce/data' );
return {
...originalModule,
- useUser: jest.fn().mockReturnValue( { currentUserCan: () => true } ),
useUserPreferences: jest.fn().mockReturnValue( {} ),
};
} );
@@ -81,6 +89,7 @@ describe( 'Layout', () => {
);
jest.useFakeTimers();
jest.clearAllMocks();
+ mockedGetCurrentUser.mockReturnValue( { id: 1, is_super_admin: true } );
} );
afterEach( () => {
@@ -107,7 +116,8 @@ describe( 'Layout', () => {
} );
describe( 'NoMatch', () => {
- const message = 'Sorry, you are not allowed to access this page.';
+ const message =
+ 'We couldn’t find that page. Check the address for a typo.';
it( 'should render a loading spinner first and then the error message after the delay', () => {
mockPath( '/incorrect-path' );
@@ -121,9 +131,166 @@ describe( 'Layout', () => {
} );
expect( screen.queryByText( 'spinner' ) ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole( 'heading', { name: 'Page not found' } )
+ ).toBeInTheDocument();
expect( screen.getByText( message ) ).toBeInTheDocument();
} );
+ it( 'should show an access denied message right away when the path matches a real page the user cannot access', () => {
+ // /setup-wizard requires manage_woocommerce.
+ mockedGetCurrentUser.mockReturnValue( {
+ id: 2,
+ is_super_admin: false,
+ capabilities: {},
+ } );
+ mockPath( '/setup-wizard' );
+ render( <Layout /> );
+
+ expect( screen.queryByText( 'spinner' ) ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole( 'heading', { name: 'Access denied' } )
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ 'You do not have permission to view this page. Ask a site administrator for help.'
+ )
+ ).toBeInTheDocument();
+ expect( screen.queryByText( message ) ).not.toBeInTheDocument();
+ } );
+
+ it( 'should keep a registered page loading until the current user resolves, not fall through to not found', () => {
+ mockedGetCurrentUser.mockReturnValue( undefined );
+ mockPath( '/setup-wizard' );
+ const { rerender } = render( <Layout /> );
+
+ // Well past the catch-all's 3-second delay.
+ act( () => {
+ jest.advanceTimersByTime( 5000 );
+ } );
+
+ expect( screen.getByText( 'spinner' ) ).toBeInTheDocument();
+ expect(
+ screen.queryByRole( 'heading', { name: 'Page not found' } )
+ ).not.toBeInTheDocument();
+ expect( screen.queryByText( message ) ).not.toBeInTheDocument();
+
+ mockedGetCurrentUser.mockReturnValue( {
+ id: 2,
+ is_super_admin: false,
+ capabilities: {},
+ } );
+ rerender( <Layout /> );
+
+ expect(
+ screen.getByRole( 'heading', { name: 'Access denied' } )
+ ).toBeInTheDocument();
+ } );
+
+ it( 'should keep a registered page loading while the current user is an unresolved empty record', () => {
+ mockedGetCurrentUser.mockReturnValue( {} );
+ mockPath( '/setup-wizard' );
+ render( <Layout /> );
+
+ act( () => {
+ jest.advanceTimersByTime( 5000 );
+ } );
+
+ expect( screen.getByText( 'spinner' ) ).toBeInTheDocument();
+ expect(
+ screen.queryByRole( 'heading', { name: 'Access denied' } )
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole( 'heading', { name: 'Page not found' } )
+ ).not.toBeInTheDocument();
+ } );
+
+ it( 'should let an open page win over a denied page whose pattern differs only by parameter name', () => {
+ const namespace = `woocommerce/woocommerce/test_${ PAGES_FILTER }`;
+ mockedGetCurrentUser.mockReturnValue( {
+ id: 2,
+ is_super_admin: false,
+ capabilities: {},
+ } );
+ // The denied page is registered first, so it would win a tie.
+ addFilter( PAGES_FILTER, namespace, ( pages ) => [
+ {
+ breadcrumbs: [ 'Denied' ],
+ container: () => <button>Denied page</button>,
+ path: '/test/item/:slug',
+ capability: 'manage_test_items',
+ },
+ {
+ breadcrumbs: [ 'Open' ],
+ container: () => <button>Open page</button>,
+ path: '/test/item/:id',
+ },
+ ...pages,
+ ] );
+
+ mockPath( '/test/item/42' );
+ render( <Layout /> );
+
+ expect(
+ screen.getByRole( 'button', { name: 'Open page' } )
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole( 'heading', { name: 'Access denied' } )
+ ).not.toBeInTheDocument();
+
+ removeFilter( PAGES_FILTER, namespace );
+ } );
+
+ it( 'should deny a path that only matches pages the user cannot open, rather than report it as not found', () => {
+ const namespace = `woocommerce/woocommerce/test_${ PAGES_FILTER }`;
+ mockedGetCurrentUser.mockReturnValue( {
+ id: 2,
+ is_super_admin: false,
+ capabilities: {},
+ } );
+ addFilter( PAGES_FILTER, namespace, ( pages ) => [
+ ...pages,
+ {
+ breadcrumbs: [ 'Denied' ],
+ container: () => <button>Denied page</button>,
+ path: '/test/secret/:slug',
+ capability: 'manage_test_items',
+ },
+ ] );
+
+ mockPath( '/test/secret/42' );
+ render( <Layout /> );
+
+ expect(
+ screen.getByRole( 'heading', { name: 'Access denied' } )
+ ).toBeInTheDocument();
+ expect( screen.queryByText( message ) ).not.toBeInTheDocument();
+
+ removeFilter( PAGES_FILTER, namespace );
+ } );
+
+ it( 'should still show a not found message for an unmatched path even when the user lacks other capabilities', () => {
+ mockedGetCurrentUser.mockReturnValue( {
+ id: 2,
+ is_super_admin: false,
+ capabilities: {},
+ } );
+ mockPath( '/this-path-matches-nothing' );
+ render( <Layout /> );
+
+ act( () => {
+ jest.runOnlyPendingTimers();
+ } );
+
+ expect(
+ screen.getByRole( 'heading', { name: 'Page not found' } )
+ ).toBeInTheDocument();
+ expect( screen.getByText( message ) ).toBeInTheDocument();
+ expect(
+ screen.queryByRole( 'heading', { name: 'Access denied' } )
+ ).not.toBeInTheDocument();
+ } );
+
it( 'should render the page added after the initial filter has been run, not show the error message', () => {
const namespace = `woocommerce/woocommerce/test_${ PAGES_FILTER }`;
const path = '/test/greeting';
@@ -159,6 +326,42 @@ describe( 'Layout', () => {
// Clean up the filter as filters are working globally.
removeFilter( PAGES_FILTER, namespace );
} );
+
+ it( 'should still render pages registered after a NoMatch screen unmounts', () => {
+ const namespace = `woocommerce/woocommerce/test_${ PAGES_FILTER }`;
+ const path = '/test/late-greeting';
+
+ mockPath( path );
+ const { rerender } = render(
+ <>
+ <Layout />
+ <NoMatch />
+ </>
+ );
+
+ // Unmounting NoMatch must not tear down the layout's listener
+ // for pages registered later.
+ rerender( <Layout /> );
+
+ act( () => {
+ addFilter( PAGES_FILTER, namespace, ( pages ) => {
+ return [
+ ...pages,
+ {
+ breadcrumbs: [ 'Late greeting' ],
+ container: () => <button>Greet late</button>,
+ path,
+ },
+ ];
+ } );
+ } );
+
+ expect(
+ screen.getByRole( 'button', { name: 'Greet late' } )
+ ).toBeInTheDocument();
+
+ removeFilter( PAGES_FILTER, namespace );
+ } );
} );
describe( 'Pages added through the pages filter', () => {
diff --git a/plugins/woocommerce/client/admin/eslint-suppressions.json b/plugins/woocommerce/client/admin/eslint-suppressions.json
index ce705652b25..f508dd18946 100644
--- a/plugins/woocommerce/client/admin/eslint-suppressions.json
+++ b/plugins/woocommerce/client/admin/eslint-suppressions.json
@@ -69,11 +69,6 @@
"count": 3
}
},
- "client/layout/NoMatch.tsx": {
- "@wordpress/use-recommended-components": {
- "count": 2
- }
- },
"client/layout/store-alerts/index.js": {
"@wordpress/use-recommended-components": {
"count": 4