Skip to content

Commit

Permalink
mock pages on mocked search response
Browse files Browse the repository at this point in the history
Necessary as the invalid links logic calls `getEntityRecord`
on pages, and if they don't exist a 404 error is thrown, causing
tests using `mocklSearchResponse` to fail, as the pages being
looked up don't exist.

Using `createPages` does not fix this issue.
  • Loading branch information
vcanales committed Jan 31, 2022
1 parent 1e74c54 commit 45e19e0
Showing 1 changed file with 53 additions and 1 deletion.
54 changes: 53 additions & 1 deletion packages/e2e-tests/specs/editor/blocks/navigation.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,47 @@ const POSTS_ENDPOINT = '/wp/v2/posts';
const PAGES_ENDPOINT = '/wp/v2/pages';
const DRAFT_PAGES_ENDPOINT = [ PAGES_ENDPOINT, { status: 'draft' } ];
const NAVIGATION_MENUS_ENDPOINT = '/wp/v2/navigation';
// todo: consolidate with logic found in navigation-editor tests
// https://github.com/WordPress/gutenberg/blob/trunk/packages/e2e-tests/specs/experiments/navigation-editor.test.js#L71
const REST_PAGES_ROUTES = [
'/wp/v2/pages',
`rest_route=${ encodeURIComponent( '/wp/v2/pages' ) }`,
];

/**
* Determines if a given URL matches any of a given collection of
* routes (expressed as substrings).
*
* @param {string} reqUrl the full URL to be tested for matches.
* @param {Array} routes array of strings to match against the URL.
*/
function matchUrlToRoute( reqUrl, routes ) {
return routes.some( ( route ) => reqUrl.includes( route ) );
}

function getEndpointMocks( matchingRoutes, responsesByMethod ) {
return [ 'GET', 'POST', 'DELETE', 'PUT' ].reduce( ( mocks, restMethod ) => {
if ( responsesByMethod[ restMethod ] ) {
return [
...mocks,
{
match: ( request ) =>
matchUrlToRoute( request.url(), matchingRoutes ) &&
request.method() === restMethod,
onRequestMatch: createJSONResponse(
responsesByMethod[ restMethod ]
),
},
];
}

return mocks;
}, [] );
}

function getPagesMocks( responsesByMethod ) {
return getEndpointMocks( REST_PAGES_ROUTES, responsesByMethod );
}

async function mockSearchResponse( items ) {
const mappedItems = items.map( ( { title, slug }, index ) => ( {
Expand All @@ -47,14 +88,25 @@ async function mockSearchResponse( items ) {
type: 'post',
url: `https://this/is/a/test/search/${ slug }`,
} ) );

await setUpResponseMocking( [
{
match: ( request ) =>
request.url().includes( `rest_route` ) &&
request.url().includes( `search` ),
onRequestMatch: createJSONResponse( mappedItems ),
},
...getPagesMocks( {
GET: [
{
type: 'page',
id: 1,
link: 'https://example.com/1',
title: {
rendered: 'My page',
},
},
],
} ),
] );
}

Expand Down

0 comments on commit 45e19e0

Please sign in to comment.