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

test(nextjs): E2E tests for middleware file placement #5037

Merged
merged 4 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions .changeset/selfish-news-invent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
9 changes: 9 additions & 0 deletions integration/models/application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export const application = (
const stdoutFilePath = path.resolve(appDirPath, `e2e.${now}.log`);
const stderrFilePath = path.resolve(appDirPath, `e2e.${now}.err.log`);
let buildOutput = '';
let serveOutput = '';

const self = {
name,
Expand Down Expand Up @@ -93,7 +94,11 @@ export const application = (
get buildOutput() {
return buildOutput;
},
get serveOutput() {
alexcarpenter marked this conversation as resolved.
Show resolved Hide resolved
return serveOutput;
},
serve: async (opts: { port?: number; manualStart?: boolean } = {}) => {
const log = logger.child({ prefix: 'serve' }).info;
const port = opts.port || (await getPort());
// TODO: get serverUrl as in dev()
const serverUrl = `http://localhost:${port}`;
Expand All @@ -102,6 +107,10 @@ export const application = (
const proc = run(scripts.serve, {
cwd: appDirPath,
env: { PORT: port.toString() },
log: (msg: string) => {
serveOutput += `\n${msg}`;
log(msg);
},
});
cleanupFns.push(() => awaitableTreekill(proc.pid, 'SIGKILL'));
await waitForIdleProcess(proc);
Expand Down
38 changes: 28 additions & 10 deletions integration/models/applicationConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type Scripts = { dev: string; build: string; setup: string; serve: string };
export const applicationConfig = () => {
let name = '';
let serverUrl = '';
const templates: string[] = [];
let template: string;
const files = new Map<string, string>();
const scripts: Scripts = { dev: 'pnpm dev', serve: 'pnpm serve', build: 'pnpm build', setup: 'pnpm install' };
const envFormatters = { public: (key: string) => key, private: (key: string) => key };
Expand All @@ -26,7 +26,9 @@ export const applicationConfig = () => {
clone.setName(name);
clone.setEnvFormatter('public', envFormatters.public);
clone.setEnvFormatter('private', envFormatters.private);
templates.forEach(t => clone.useTemplate(t));
if (template) {
clone.useTemplate(template);
}
dependencies.forEach((v, k) => clone.addDependency(k, v));
Object.entries(scripts).forEach(([k, v]) => clone.addScript(k as keyof typeof scripts, v));
files.forEach((v, k) => clone.addFile(k, () => v));
Expand All @@ -44,8 +46,12 @@ export const applicationConfig = () => {
files.set(filePath, cbOrPath(helpers));
return self;
},
removeFile: (filePath: string) => {
files.set(filePath, '');
return self;
},
useTemplate: (path: string) => {
templates.push(path);
template = path;
return self;
},
setEnvFormatter: (type: keyof typeof envFormatters, formatter: typeof envFormatters.public) => {
Expand Down Expand Up @@ -76,20 +82,32 @@ export const applicationConfig = () => {
const appDirPath = path.resolve(constants.TMP_DIR, appDirName);

// Copy template files
for (const template of templates) {
if (template) {
logger.info(`Copying template "${path.basename(template)}" -> ${appDirPath}`);
await fs.ensureDir(appDirPath);
await fs.copy(template, appDirPath, { overwrite: true, filter: (p: string) => !p.includes('node_modules') });
}

await Promise.all(
[...files]
.filter(([, contents]) => !contents)
.map(async ([pathname]) => {
const dest = path.resolve(appDirPath, pathname);
logger.info(`Deleting file ${dest}`);
await fs.remove(dest);
}),
);

// Create individual files
await Promise.all(
[...files].map(async ([pathname, contents]) => {
const dest = path.resolve(appDirPath, pathname);
logger.info(`Copying file "${pathname}" -> ${dest}`);
await fs.ensureFile(dest);
await fs.writeFile(dest, contents);
}),
[...files]
.filter(([, contents]) => contents)
.map(async ([pathname, contents]) => {
const dest = path.resolve(appDirPath, pathname);
logger.info(`Copying file "${pathname}" -> ${dest}`);
await fs.ensureFile(dest);
await fs.writeFile(dest, contents);
}),
);

// Adjust package.json dependencies
Expand Down
115 changes: 115 additions & 0 deletions integration/tests/middleware-placement.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { expect, test } from '@playwright/test';

import type { Application } from '../models/application';
import { appConfigs } from '../presets';
import { createTestUtils } from '../testUtils';

const commonSetup = appConfigs.next.appRouterQuickstart.clone().removeFile('src/middleware.ts');
alexcarpenter marked this conversation as resolved.
Show resolved Hide resolved

test.describe('next start - missing middleware @quickstart', () => {
alexcarpenter marked this conversation as resolved.
Show resolved Hide resolved
test.describe.configure({ mode: 'parallel' });
let app: Application;

test.beforeAll(async () => {
app = await commonSetup.commit();
await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodesQuickstart);
await app.build();
await app.serve();
});

test.afterAll(async () => {
await app.teardown();
});

test('Display error for missing middleware', async ({ page, context }) => {
const u = createTestUtils({ app, page, context });
await u.page.goToAppHome();

expect(app.serveOutput).toContain('Your Middleware exists at ./src/middleware.(ts|js)');
});
});

test.describe('next start - invalid middleware at root on src/ @quickstart', () => {
test.describe.configure({ mode: 'parallel' });
let app: Application;

test.beforeAll(async () => {
app = await commonSetup
.addFile(
'middleware.ts',
() => `
import { clerkMiddleware } from '@clerk/nextjs/server';
export default clerkMiddleware();

export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
`,
)
.commit();
await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodesQuickstart);
await app.build();
await app.serve();
});

test.afterAll(async () => {
await app.teardown();
});

test('Display suggestion for moving middleware to from `./middleware.ts` to `./src/middleware.ts`', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });
await u.page.goToAppHome();

expect(app.serveOutput).not.toContain('Your Middleware exists at ./src/middleware.(ts|js)');
expect(app.serveOutput).toContain(
'Clerk: clerkMiddleware() was not run, your middleware file might be misplaced. Move your middleware file to ./src/middleware.ts. Currently located at ./middleware.ts',
);
});
});

test.describe('next start - invalid middleware inside app on src/ @quickstart', () => {
test.describe.configure({ mode: 'parallel' });
let app: Application;

test.beforeAll(async () => {
app = await commonSetup
.addFile(
'src/app/middleware.ts',
() => `
import { clerkMiddleware } from '@clerk/nextjs/server';
export default clerkMiddleware();

export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};
`,
)
.commit();
await app.setup();
await app.withEnv(appConfigs.envs.withEmailCodesQuickstart);
// await app.dev({ allowFailures: true });
await app.build();
await app.serve();
});

test.afterAll(async () => {
await app.teardown();
});

test('Display suggestion for moving middleware to from `./src/app/middleware.ts` to `./src/middleware.ts`', async ({
page,
context,
}) => {
const u = createTestUtils({ app, page, context });
await u.page.goToAppHome();
expect(app.serveOutput).not.toContain('Your Middleware exists at ./src/middleware.(ts|js)');
expect(app.serveOutput).toContain(
'Clerk: clerkMiddleware() was not run, your middleware file might be misplaced. Move your middleware file to ./src/middleware.ts. Currently located at ./src/app/middleware.ts',
);
});
});