Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

App Router Handler Tests #799

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions packages/core/test/server-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ interface TestEndpointResponse {

export const VALID_AUTH_TOKEN = 'this is a valid auth';
export const DRAFT_POST_ID = 57;
export const VALID_REVALIDATE_AUTH_TOKEN = 'this is a valid revalidate auth token';
export const REVALIDATE_PATH = '/revalidate-path';
export const REVALIDATE_POST_ID = 57;

const handlers = [
rest.head('http://example.com/redirect-test', (req, res) => {
Expand Down Expand Up @@ -348,6 +351,28 @@ const handlers = [

return res(ctx.json([]));
}),

rest.get('https://js1.10up.com/wp-json/headless-wp/v1/token', (req, res, ctx) => {
if (
(req.headers.has('Authorization') &&
req.headers.get('Authorization') === `Bearer ${VALID_REVALIDATE_AUTH_TOKEN}`) ||
(req.headers.has('X-HeadstartWP-Authorization') &&
req.headers.get('X-HeadstartWP-Authorization') ===
`Bearer ${VALID_REVALIDATE_AUTH_TOKEN}`)
) {
return res(ctx.json({ post_id: REVALIDATE_POST_ID, path: REVALIDATE_PATH }));
}

return res(
ctx.json({
code: 'rest_cannot_read',
message: 'Sorry, you are not allowed to do this.',
data: {
status: 401,
},
}),
);
}),
];

export { handlers };
19 changes: 17 additions & 2 deletions packages/core/test/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { handlers, VALID_AUTH_TOKEN, DRAFT_POST_ID } from './server-handlers';
import {
handlers,
VALID_AUTH_TOKEN,
DRAFT_POST_ID,
VALID_REVALIDATE_AUTH_TOKEN,
REVALIDATE_PATH,
REVALIDATE_POST_ID,
} from './server-handlers';

const server = setupServer(...handlers);
export { server, rest, VALID_AUTH_TOKEN, DRAFT_POST_ID };
export {
server,
rest,
VALID_AUTH_TOKEN,
DRAFT_POST_ID,
VALID_REVALIDATE_AUTH_TOKEN,
REVALIDATE_PATH,
REVALIDATE_POST_ID,
};
2 changes: 1 addition & 1 deletion packages/next/jest.setup.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import 'whatwg-fetch';
import 'isomorphic-fetch';

import { server } from '@headstartwp/core/test';

Expand Down
2 changes: 1 addition & 1 deletion packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
"node-mocks-http": "^1.14.1",
"ts-jest": "^29.0.1",
"typescript": "^5.4.5",
"whatwg-fetch": "^3.6.20",
"isomorphic-fetch": "^3.0.0",
"jest-fetch-mock": "^3.0.3",
"tsc-esm-fix": "^2.20.27",
"@types/react": "^18",
Expand Down
207 changes: 205 additions & 2 deletions packages/next/src/rsc/handlers/__tests__/previewRouteHandler.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,29 @@
import nextHeaders from 'next/headers';
import { NextRequest } from 'next/server';
import { previewRouteHandler } from '../previewRouteHandler';
import { setHeadstartWPConfig } from '@headstartwp/core';
import { DRAFT_POST_ID, VALID_AUTH_TOKEN } from '@headstartwp/core/test';
import { redirect } from 'next/navigation';
import { COOKIE_NAME, previewRouteHandler } from '../previewRouteHandler';

jest.mock('next/headers', () => ({
draftMode: () => ({ isEnabled: false, enable: jest.fn() }),
cookies: jest.fn(() => ({
get: jest.fn(),
has: jest.fn(),
})),
}));

const config = {
sourceUrl: 'https://js1.10up.com',
useWordPressPlugin: true,
};

describe('previewRouteHandler', () => {
it.skip('does not accepts POST requests', async () => {
beforeEach(() => {
setHeadstartWPConfig(config);
});

it('does not accepts POST requests', async () => {
const req = new NextRequest('http://test.com', {
method: 'POST',
body: JSON.stringify({}),
Expand All @@ -12,4 +33,186 @@ describe('previewRouteHandler', () => {

expect(res.status).toBe(401);
});

it('does not accepts invalid params', async () => {
const req = new NextRequest('http://test.com');

const res = await previewRouteHandler(req);

expect(res.status).toBe(401);
});

it('fails if a valid auth token is not provided', async () => {
const searchParams = new URLSearchParams({
post_id: DRAFT_POST_ID.toString(),
token: 'test',
post_type: 'post',
});

const req = new NextRequest(`https://js1.10up.com?${searchParams.toString()}`);

await expect(() => previewRouteHandler(req)).rejects.toThrow(
'Sorry, you are not allowed to view this post.',
);
});

it('works if a valid auth token is provided', async () => {
const searchParams = new URLSearchParams({
post_id: DRAFT_POST_ID.toString(),
token: VALID_AUTH_TOKEN.toString(),
post_type: 'post',
});

const req = new NextRequest(`https://js1.10up.com?${searchParams.toString()}`);

const previewDataPayload = JSON.stringify({
id: DRAFT_POST_ID,
postType: 'post',
revision: false,
authToken: VALID_AUTH_TOKEN,
});

// @ts-expect-error
nextHeaders.cookies.mockReturnValue({
set: jest.fn(),
get: jest.fn(() => ({ value: previewDataPayload, name: COOKIE_NAME })),
has: jest.fn(() => true),
});

await expect(() => previewRouteHandler(req)).rejects.toThrow('NEXT_REDIRECT');

expect(nextHeaders.cookies().set).toHaveBeenCalledWith(COOKIE_NAME, previewDataPayload, {
httpOnly: true,
maxAge: 300,
path: '/modi-qui-dignissimos-sed-assumenda-sint-iusto',
});
});

it('works for custom post types', async () => {
setHeadstartWPConfig({
...config,
customPostTypes: [
{
slug: 'book',
// reuse existing posts endpoint
endpoint: '/wp-json/wp/v2/posts',
// these should match your file-system routing
single: '/book',
archive: '/books',
},
],
});

const searchParams = new URLSearchParams({
post_id: DRAFT_POST_ID.toString(),
token: VALID_AUTH_TOKEN.toString(),
post_type: 'book',
});

const previewDataPayload = JSON.stringify({
id: DRAFT_POST_ID,
postType: 'book',
revision: false,
authToken: VALID_AUTH_TOKEN,
});

const req = new NextRequest(`https://js1.10up.com?${searchParams.toString()}`);

await expect(() => previewRouteHandler(req)).rejects.toThrow('NEXT_REDIRECT');
expect(nextHeaders.cookies().set).toHaveBeenCalledWith(COOKIE_NAME, previewDataPayload, {
httpOnly: true,
maxAge: 300,
path: '/book/modi-qui-dignissimos-sed-assumenda-sint-iusto',
});
});

it('works for custom post types with locale', async () => {
setHeadstartWPConfig({
...config,
customPostTypes: [
{
slug: 'book',
// reuse existing posts endpoint
endpoint: '/wp-json/wp/v2/posts',
// these should match your file-system routing
single: '/book',
archive: '/books',
},
],
});

const searchParams = new URLSearchParams({
post_id: DRAFT_POST_ID.toString(),
token: VALID_AUTH_TOKEN.toString(),
post_type: 'book',
locale: 'es',
});

const previewDataPayload = JSON.stringify({
id: DRAFT_POST_ID,
postType: 'book',
revision: false,
authToken: VALID_AUTH_TOKEN,
});

const req = new NextRequest(`https://js1.10up.com?${searchParams.toString()}`);

await expect(() => previewRouteHandler(req)).rejects.toThrow('NEXT_REDIRECT');

expect(nextHeaders.cookies().set).toHaveBeenCalledWith(COOKIE_NAME, previewDataPayload, {
httpOnly: true,
maxAge: 300,
path: '/es/book/modi-qui-dignissimos-sed-assumenda-sint-iusto',
});
});

it('correctly takes into account `options`', async () => {
const searchParams = new URLSearchParams({
post_id: DRAFT_POST_ID.toString(),
token: VALID_AUTH_TOKEN.toString(),
post_type: 'post',
});

const req = new NextRequest(`https://js1.10up.com?${searchParams.toString()}`);

const onRedirect = jest.fn(() => {
redirect('/');
});

await expect(() =>
previewRouteHandler(req, {
preparePreviewData({ previewData }) {
return { ...previewData, myCustomData: true };
},
getRedirectPath({ defaultRedirectPath }) {
return `${defaultRedirectPath}-preview=true`;
},
onRedirect,
}),
).rejects.toThrow('NEXT_REDIRECT');

expect(nextHeaders.cookies().set).toHaveBeenCalledWith(
COOKIE_NAME,
JSON.stringify({
id: DRAFT_POST_ID,
postType: 'post',
revision: false,
authToken: VALID_AUTH_TOKEN,
myCustomData: true,
}),
{
httpOnly: true,
maxAge: 300,
path: '/modi-qui-dignissimos-sed-assumenda-sint-iusto-preview=true',
},
);

expect(onRedirect).toHaveBeenCalledWith({
redirectPath: '/modi-qui-dignissimos-sed-assumenda-sint-iusto-preview=true',
post: expect.any(Object),
postTypeDef: expect.any(Object),
previewData: expect.any(Object),
req,
});
});
});
Loading
Loading