Skip to content

Commit 045c301

Browse files
committed
test(chrome-extension): cover development and production auth flows
1 parent 8a9990c commit 045c301

4 files changed

Lines changed: 126 additions & 16 deletions

File tree

‎integration/templates/chrome-extension-vite/src/popup.tsx‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
1-
import { ClerkProvider, Show, SignIn, UserButton, useAuth } from '@clerk/chrome-extension';
1+
import { ClerkProvider, Show, SignIn, SignUp, UserButton, useAuth } from '@clerk/chrome-extension';
22
import React from 'react';
33
import ReactDOM from 'react-dom/client';
44

55
const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string;
66

77
function App() {
8+
const [signingUp, setSigningUp] = React.useState(false);
9+
810
return (
911
<ClerkProvider
1012
publishableKey={PUBLISHABLE_KEY}
@@ -13,7 +15,13 @@ function App() {
1315
>
1416
<main>
1517
<Show when='signed-out'>
16-
<SignIn />
18+
{signingUp ? <SignUp /> : <SignIn />}
19+
<button
20+
type='button'
21+
onClick={() => setSigningUp(value => !value)}
22+
>
23+
{signingUp ? 'Back to sign in' : 'Create account'}
24+
</button>
1725
</Show>
1826
<Show when='signed-in'>
1927
<UserButton />
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import type { ClerkClient } from '@clerk/backend';
2+
import { createPageObjects } from '@clerk/testing/playwright/unstable';
3+
4+
import { appConfigs } from '../../presets';
5+
import { createTestUtils } from '../../testUtils';
6+
import { createEmailService } from '../../testUtils/emailService';
7+
import type { FakeUser, UserService } from '../../testUtils/usersService';
8+
import { expect, test as extensionTest } from './fixtures';
9+
10+
for (const environmentType of ['development', 'production'] as const) {
11+
const test = extensionTest.extend({
12+
extensionEnv: [
13+
environmentType === 'production' ? appConfigs.envs.sessionsProd1 : appConfigs.envs.withEmailCodes,
14+
{ scope: 'worker' },
15+
],
16+
extensionTestingToken: [false, { scope: 'worker' }],
17+
});
18+
19+
test.describe(`chrome extension ${environmentType} auth @chrome-extension`, () => {
20+
test.describe.configure({ mode: 'serial' });
21+
22+
let services: { clerk: ClerkClient; users: UserService };
23+
let user: FakeUser;
24+
let addedOrigin: string | undefined;
25+
26+
test.beforeAll(async ({ extensionApp }) => {
27+
const publishableKey = extensionApp.env.publicVariables.get('CLERK_PUBLISHABLE_KEY');
28+
expect(publishableKey?.startsWith(environmentType === 'production' ? 'pk_live_' : 'pk_test_')).toBe(true);
29+
({ services } = await createTestUtils({ app: extensionApp }));
30+
});
31+
32+
test.beforeEach(async ({ extensionId }) => {
33+
user = services.users.createFakeUser(test, {
34+
fictionalEmail: environmentType === 'development',
35+
});
36+
37+
if (environmentType === 'production') {
38+
const origin = `chrome-extension://${extensionId}`;
39+
const instance = await services.clerk.instance.get();
40+
if (!instance.allowedOrigins?.includes(origin)) {
41+
await services.clerk.instance.update({ allowedOrigins: [...(instance.allowedOrigins || []), origin] });
42+
addedOrigin = origin;
43+
}
44+
}
45+
});
46+
47+
test.afterEach(async () => {
48+
try {
49+
await user?.deleteIfExists();
50+
} finally {
51+
if (addedOrigin) {
52+
const instance = await services.clerk.instance.get();
53+
await services.clerk.instance.update({
54+
allowedOrigins: (instance.allowedOrigins || []).filter(origin => origin !== addedOrigin),
55+
});
56+
addedOrigin = undefined;
57+
}
58+
}
59+
});
60+
61+
test('signs in with email and password without a Testing Token', async ({ extensionPage }) => {
62+
await services.users.createBapiUser(user);
63+
const { signIn } = createPageObjects({ page: extensionPage, useTestingToken: false });
64+
await signIn.waitForMounted();
65+
await signIn.setIdentifier(user.email!);
66+
await signIn.continue();
67+
await signIn.getPasswordInput().fill(user.password);
68+
await signIn.continue();
69+
await expect(extensionPage.getByTestId('user-id')).toHaveText(/^user_/);
70+
await expect(extensionPage.getByTestId('session-id')).toHaveText(/^sess_/);
71+
});
72+
73+
test('signs up with email and password without a Testing Token', async ({ extensionPage }) => {
74+
await extensionPage.getByRole('button', { name: 'Create account', exact: true }).click();
75+
const { signUp } = createPageObjects({ page: extensionPage, useTestingToken: false });
76+
await signUp.waitForMounted();
77+
await signUp.signUpWithEmailAndPassword({ email: user.email, password: user.password });
78+
79+
if (environmentType === 'development') {
80+
await signUp.enterTestOtpCode();
81+
} else {
82+
const code = await createEmailService().getCodeForEmailAddress(user.email!);
83+
await signUp.enterOtpCode(code);
84+
}
85+
86+
await expect(extensionPage.getByTestId('user-id')).toHaveText(/^user_/);
87+
await expect(extensionPage.getByTestId('session-id')).toHaveText(/^sess_/);
88+
});
89+
});
90+
}

‎integration/tests/chrome-extension/fixtures.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
import * as path from 'node:path';
22

3-
import { test as base } from '@playwright/test';
43
import type { BrowserContext, Page } from '@playwright/test';
4+
import { test as base } from '@playwright/test';
55

6-
import { appConfigs } from '../../presets';
76
import type { Application } from '../../models/application';
7+
import type { EnvironmentConfig } from '../../models/environment';
8+
import { appConfigs } from '../../presets';
89
import { getExtensionId, launchExtensionContext, setupClerkTestingEnv } from './helpers';
910

1011
type WorkerFixtures = {
1112
extensionDistPath: string;
1213
extensionApp: Application;
14+
extensionEnv: EnvironmentConfig;
15+
extensionTestingToken: boolean;
1316
};
1417

1518
type TestFixtures = {
@@ -25,18 +28,21 @@ type TestFixtures = {
2528
* Test-scoped fixtures create a fresh persistent context per test.
2629
*/
2730
export const test = base.extend<TestFixtures, WorkerFixtures>({
31+
extensionEnv: [appConfigs.envs.withEmailCodes, { scope: 'worker', option: true }],
32+
extensionTestingToken: [true, { scope: 'worker', option: true }],
2833
// Worker-scoped: build the extension once and set up testing tokens
2934
extensionApp: [
30-
async ({}, use) => {
31-
const env = appConfigs.envs.withEmailCodes;
35+
async ({ extensionEnv: env, extensionTestingToken }, use) => {
3236
const config = appConfigs.chromeExtension.vite;
3337

3438
const app = await config.commit();
3539
await app.withEnv(env);
3640
await app.setup();
3741
await app.build();
3842

39-
await setupClerkTestingEnv(env);
43+
if (extensionTestingToken) {
44+
await setupClerkTestingEnv(env);
45+
}
4046

4147
await use(app);
4248
await app.teardown();
@@ -53,8 +59,11 @@ export const test = base.extend<TestFixtures, WorkerFixtures>({
5359
],
5460

5561
// Test-scoped: fresh persistent context per test with the extension loaded
56-
context: async ({ extensionDistPath }, use) => {
57-
const context = await launchExtensionContext(extensionDistPath, { bypassCSP: true });
62+
context: async ({ extensionDistPath, extensionTestingToken }, use) => {
63+
const context = await launchExtensionContext(extensionDistPath, {
64+
bypassCSP: false,
65+
testingToken: extensionTestingToken,
66+
});
5867
await use(context);
5968
await context.close();
6069
},

‎integration/tests/chrome-extension/helpers.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
11
import { createClerkClient as backendCreateClerkClient } from '@clerk/backend';
22
import { parsePublishableKey } from '@clerk/shared/keys';
33
import { clerkSetup, setupClerkTestingToken } from '@clerk/testing/playwright';
4+
import type { BrowserContext, Page } from '@playwright/test';
45
import { chromium } from '@playwright/test';
5-
import type { BrowserContext } from '@playwright/test';
66

77
import type { EnvironmentConfig } from '../../models/environment';
88
import { withRetry } from '../../testUtils/retryableClerkClient';
9-
import { createUserService } from '../../testUtils/usersService';
109
import type { FakeUser, PlaywrightTest } from '../../testUtils/usersService';
10+
import { createUserService } from '../../testUtils/usersService';
1111

1212
/**
1313
* Query the background service worker for auth state via chrome.runtime.sendMessage.
1414
*/
15-
export function getAuthFromBackground(
16-
page: import('@playwright/test').Page,
17-
): Promise<{ userId: string | null; sessionId: string | null }> {
15+
export function getAuthFromBackground(page: Page): Promise<{ userId: string | null; sessionId: string | null }> {
1816
return page.evaluate(() => {
1917
return new Promise(resolve => {
2018
chrome.runtime.sendMessage({ type: 'GET_AUTH' }, (response: any) => {
@@ -50,7 +48,10 @@ export async function setupClerkTestingEnv(env: EnvironmentConfig) {
5048
/**
5149
* Launch a persistent Chromium context with a Chrome extension loaded.
5250
*/
53-
export async function launchExtensionContext(extensionDistPath: string, opts?: { bypassCSP?: boolean }) {
51+
export async function launchExtensionContext(
52+
extensionDistPath: string,
53+
opts?: { bypassCSP?: boolean; testingToken?: boolean },
54+
) {
5455
const context = await chromium.launchPersistentContext('', {
5556
headless: false,
5657
bypassCSP: opts?.bypassCSP,
@@ -61,7 +62,9 @@ export async function launchExtensionContext(extensionDistPath: string, opts?: {
6162
],
6263
});
6364

64-
await setupClerkTestingToken({ context });
65+
if (opts?.testingToken !== false) {
66+
await setupClerkTestingToken({ context });
67+
}
6568
return context;
6669
}
6770

0 commit comments

Comments
 (0)