Skip to content
Draft
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
2 changes: 1 addition & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export default {
],
moduleFileExtensions: ['ts', 'tsx', 'js'],
modulePathIgnorePatterns: ['<rootDir>/sdk-debug/'],
testPathIgnorePatterns: ['<rootDir>/playwright/', '<rootDir>/mobile-e2e/'],
testPathIgnorePatterns: ['<rootDir>/playwright/', '<rootDir>/mobile-e2e/', '<rootDir>/stress-test/'],
setupFiles: ['dotenv/config', '@serh11p/jest-webextension-mock', 'fake-indexeddb/auto'],
setupFilesAfterEnv: ['./jest.setup.js']
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"mobile:ios:export": "xcodebuild -exportArchive -archivePath ios/App/build/MidenWallet.xcarchive -exportPath ios/App/build/export -exportOptionsPlist ios/App/ExportOptions.plist",
"zip": "ts-node --project ./tsconfig-utility.json ./utility/buildZip.ts",
"test": "jest",
"stress-test": "playwright test --project=stress",
"test-debug": "node --inspect-brk node_modules/.bin/jest --runInBand",
"test:coverage": "jest --coverage",
"test:smoke": "jest src/lib/miden/smoke.integration.test.ts",
Expand Down
27 changes: 17 additions & 10 deletions playwright.config.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,27 @@
import { defineConfig } from '@playwright/test';

export default defineConfig({
testDir: './playwright/tests',
timeout: 30_000,
expect: {
timeout: 10_000,
},
// Browser extension tests are flaky when run in parallel due to Chrome/extension resource conflicts
fullyParallel: false,
forbidOnly: !!process.env.CI,
retries: 2,
workers: 1,
reporter: [['list']],
use: {
headless: true,
trace: 'on-first-retry',
trace: 'on-first-retry'
},
projects: [
{
name: 'default',
testDir: './playwright/tests',
timeout: 30_000,
use: { headless: true },
retries: 2
},
{
name: 'stress',
testDir: './stress-test',
timeout: 7_200_000, // 2 hours
use: { headless: false }, // extensions require headed mode
retries: 0
}
]
});

76 changes: 76 additions & 0 deletions stress-test/fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { chromium, test as base } from '@playwright/test';
import { execSync } from 'child_process';
import fs from 'fs';
import os from 'os';
import path from 'path';

type Fixtures = {
extensionPath: string;
extensionId: string;
extensionContext: import('@playwright/test').BrowserContext;
};

const ROOT_DIR = path.resolve(__dirname, '..');
const DEFAULT_EXTENSION_PATH = path.join(ROOT_DIR, 'dist', 'chrome_unpacked');

function ensureExtensionBuilt(extensionPath: string) {
const manifestPath = path.join(extensionPath, 'manifest.json');
if (fs.existsSync(manifestPath) || process.env.SKIP_EXTENSION_BUILD === 'true') {
return;
}

const env = { ...process.env };
env.DISABLE_TS_CHECKER = 'true';
// Use REAL testnet client — override any default
env.MIDEN_USE_MOCK_CLIENT = 'false';

execSync('yarn build:chrome', {
cwd: ROOT_DIR,
stdio: 'inherit',
env
});
}

export const test = base.extend<Fixtures>({
extensionPath: async ({}, use) => {
const extensionPath = process.env.EXTENSION_DIST ?? DEFAULT_EXTENSION_PATH;
ensureExtensionBuilt(extensionPath);
await use(extensionPath);
},

extensionContext: [
async ({ extensionPath }, use) => {
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'miden-stress-'));

const context = await chromium.launchPersistentContext(userDataDir, {
headless: false,
args: [`--disable-extensions-except=${extensionPath}`, `--load-extension=${extensionPath}`],
ignoreDefaultArgs: ['--disable-extensions']
});

await use(context);

await context.close();
fs.rmSync(userDataDir, { recursive: true });
},
{ timeout: 120_000 }
],

extensionId: [
async ({ extensionContext }, use) => {
const serviceWorker =
extensionContext.serviceWorkers()[0] ??
(await extensionContext.waitForEvent('serviceworker', { timeout: 60_000 }));

const extensionId = new URL(serviceWorker.url()).host;

// Wait for the extension to fully initialize (IndexedDB, WASM, state)
await new Promise(resolve => setTimeout(resolve, 2_000));

await use(extensionId);
},
{ timeout: 120_000 }
]
});

export const expect = test.expect;
133 changes: 133 additions & 0 deletions stress-test/helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import type { Page } from '@playwright/test';

import { WalletMessageType, WalletStatus } from 'lib/shared/types';
import { WalletType } from 'screens/onboarding/types';

const FAUCET_API_BASE = 'https://api.midenbrowserwallet.com/mint';

/**
* Send a message to the extension's background service worker via a persistent
* INTERCOM port (matching the real IntercomClient protocol).
*/
export async function sendWalletMessage(page: Page, message: any): Promise<any> {
return await page.evaluate(
(msg: any) =>
new Promise((resolve, reject) => {
const port = chrome.runtime.connect({ name: 'INTERCOM' });
const reqId = Date.now() + Math.random();

const listener = (response: any) => {
if (response?.reqId !== reqId) return;
port.onMessage.removeListener(listener);
port.disconnect();
if (response.type === 'INTERCOM_RESPONSE') {
resolve(response.data);
} else if (response.type === 'INTERCOM_ERROR') {
reject(new Error(JSON.stringify(response.data)));
}
};

port.onMessage.addListener(listener);
port.postMessage({
type: 'INTERCOM_REQUEST',
data: msg,
reqId
});
}),
message
);
}

/**
* Get the current wallet state from the background service worker.
*/
export async function getState(page: Page): Promise<any> {
const res = await sendWalletMessage(page, { type: WalletMessageType.GetStateRequest });
return res?.state;
}

/**
* Ensure the wallet is ready (create or unlock as needed).
*/
export async function ensureWalletReady(page: Page, password: string, mnemonic?: string): Promise<any> {
for (let i = 0; i < 10; i++) {
const state = await getState(page);
const status = state?.status;
// WalletStatus is a numeric enum: Idle=0, Locked=1, Ready=2
if (status === WalletStatus.Ready) {
return state;
}
if (status === WalletStatus.Locked) {
await sendWalletMessage(page, { type: WalletMessageType.UnlockRequest, password });
} else {
await sendWalletMessage(page, {
type: WalletMessageType.NewWalletRequest,
password,
mnemonic,
ownMnemonic: !!mnemonic
});
}
await page.waitForTimeout(1_000);
}
throw new Error('Wallet not ready after retries');
}

/**
* Create a new HD account in the wallet.
*/
export async function createAccount(page: Page, walletType: WalletType, name: string): Promise<void> {
await sendWalletMessage(page, {
type: WalletMessageType.CreateAccountRequest,
walletType,
name
});
// Wait for state to propagate
await page.waitForTimeout(500);
}

/**
* Switch the active account in the wallet.
*/
export async function switchAccount(page: Page, publicKey: string): Promise<void> {
await sendWalletMessage(page, {
type: WalletMessageType.UpdateCurrentAccountRequest,
accountPublicKey: publicKey
});
await page.waitForTimeout(500);
}

/**
* Fund an account via the faucet API.
* Requests 100 MDN (10000000000 base units).
*/
export async function fundAccount(bech32Address: string): Promise<Response> {
const url = `${FAUCET_API_BASE}/${bech32Address}/10000000000`;
console.log(`Funding account: ${url}`);
const res = await fetch(url);
if (!res.ok) {
throw new Error(`Faucet request failed: ${res.status} ${res.statusText}`);
}
return res;
}

/**
* Wait for the MIDEN token balance to appear on the Explore page.
*/
export async function waitForBalance(page: Page, timeoutMs: number = 120_000): Promise<void> {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
await page.waitForTimeout(2_000);
const midenVisible = await page
.locator('text=MDN')
.first()
.isVisible()
.catch(() => false);
console.log(`[waitForBalance] Checking for balance visibility: ${midenVisible}`); // Debug log
if (midenVisible) {
return;
}
await page.waitForTimeout(3_000);
await page.reload({ waitUntil: 'domcontentloaded' });
}
throw new Error(`Balance did not appear within ${timeoutMs}ms`);
}
Loading
Loading