AFFiNE/tests/kit/playwright.ts

99 lines
2.7 KiB
TypeScript
Raw Normal View History

2023-04-28 09:40:44 +03:00
import { ok } from 'node:assert';
2023-02-17 10:33:32 +03:00
import crypto from 'node:crypto';
2023-02-05 13:41:18 +03:00
import fs from 'node:fs';
2023-04-28 09:40:44 +03:00
import path, { resolve } from 'node:path';
2023-02-05 13:41:18 +03:00
import process from 'node:process';
2023-02-17 10:33:32 +03:00
2023-07-13 15:41:46 +03:00
import type { Workspace } from '@blocksuite/store';
2023-02-17 10:33:32 +03:00
import { test as baseTest } from '@playwright/test';
2023-02-05 13:41:18 +03:00
2023-04-28 09:40:44 +03:00
export const rootDir = resolve(__dirname, '..', '..');
// assert that the rootDir is the root of the project
2023-06-29 07:13:35 +03:00
ok(
// eslint-disable-next-line @typescript-eslint/no-var-requires
require(resolve(rootDir, 'package.json')).name.toLowerCase() ===
'@affine/monorepo'
);
2023-04-28 09:40:44 +03:00
export const testResultDir = resolve(rootDir, 'test-results');
export const istanbulTempDir = process.env.ISTANBUL_TEMP_DIR
2023-02-05 13:41:18 +03:00
? path.resolve(process.env.ISTANBUL_TEMP_DIR)
: path.join(rootDir, '.nyc_output');
2023-02-05 13:41:18 +03:00
function generateUUID() {
return crypto.randomUUID();
}
export const enableCoverage = !!process.env.CI || !!process.env.COVERAGE;
2023-02-05 13:41:18 +03:00
2023-07-13 15:41:46 +03:00
type CurrentWorkspace = {
id: string;
flavour: string;
blockSuiteWorkspace: Workspace;
};
export const test = baseTest.extend<{
workspace: {
current: () => Promise<CurrentWorkspace>;
};
}>({
workspace: async ({ page }, use) => {
await use({
current: async () => {
return await page.evaluate(async () => {
2023-07-18 19:53:10 +03:00
if (!(globalThis as any).currentWorkspace) {
await new Promise<void>((resolve, reject) => {
globalThis.addEventListener(
'affine:workspace:change',
() => resolve(),
{
once: true,
}
);
setTimeout(() => reject(new Error('timeout')), 2000);
});
}
2023-07-13 15:41:46 +03:00
return (globalThis as any).currentWorkspace;
});
},
});
},
2023-02-05 13:41:18 +03:00
context: async ({ context }, use) => {
if (enableCoverage) {
await context.addInitScript(() =>
window.addEventListener('beforeunload', () =>
// @ts-expect-error
window.collectIstanbulCoverage(JSON.stringify(window.__coverage__))
)
);
await fs.promises.mkdir(istanbulTempDir, { recursive: true });
await context.exposeFunction(
'collectIstanbulCoverage',
(coverageJSON?: string) => {
if (coverageJSON)
fs.writeFileSync(
path.join(
istanbulTempDir,
`playwright_coverage_${generateUUID()}.json`
),
coverageJSON
);
}
);
}
2023-02-05 13:41:18 +03:00
await use(context);
2023-02-05 13:41:18 +03:00
if (enableCoverage) {
for (const page of context.pages()) {
await page.evaluate(() =>
// @ts-expect-error
window.collectIstanbulCoverage(JSON.stringify(window.__coverage__))
);
}
}
},
});