mirror of
https://github.com/electron/electron.git
synced 2026-10-28 11:44:46 +08:00
* test: assert with vitest's matchers instead of chai
Every assertion moves from chai's chainable language to vitest's own
matchers, so an assertion is always a call and never a bare property read:
- `to.equal` → `toBe`, `to.deep.equal`/`eql` → `toEqual`, `to.be.true` →
`toBe(true)`, `to.have.property` → `toHaveProperty`, `to.include` →
`toContain`/`toMatchObject`/`toContainEqual`, `to.be.a('string')` →
`toBeTypeOf('string')`, `instanceOf` → `toBeInstanceOf`, `lengthOf` →
`toHaveLength`, `above`/`least`/`below`/`most` → `toBeGreaterThan` and
friends, `match` → `toMatch`, `throw` → `toThrow`, `oneOf` → `toContain`
with the operands swapped, `closeTo(e, d)` → `Math.abs(x - e) <= d`,
`members`/`keys` → `arrayContaining`/`Object.keys`. A chain that kept
going after `.property()` or `.a()` becomes one matcher where vitest has
one (`toHaveProperty(key, expect.any(String))`) and separate assertions
otherwise. chai-as-promised becomes `.resolves`/`.rejects`, a failed
manual check is `assert.fail()` rather than `new chai.AssertionError`.
- vitest reports promise assertions that are not awaited; the app badge,
webview zoom and `import('electron')` specs had some that never ran and
now do (the service worker badge ones waited for a count the worker had
already cleared, so those just check the worker's answer; the zoom fixture
issued loadURL() from dom-ready, which aborts, and now waits for the load).
- Code that runs outside the spec module graph (itremote bodies in a
renderer, the utility-process net harness, two crash-case apps) is
CommonJS and vitest refuses `require('vitest')`, so it loads the same
module through spec/lib/vitest-cjs.cjs.
- A lint rule (script/lint-plugins/no-chai-assertions.mjs) rejects chai
chains on `expect()`, and no-unused-expressions is on for the specs, so
neither form of property-style assertion can come back.
- chai, chai-as-promised, dirty-chai and their @types leave
spec/package.json; the refresh-page fixture served chai.js only as "a
large script" and serves the jquery fixture instead.
* test: return promises instead of taking mocha's `done` callback
vitest has no `done` parameter. The tests and hooks that used one now
return a promise instead; where the callback was only ever called as
`done()` it is the promise's `resolve`, and where it was also handed to an
error-first API or called as `done(error)` it keeps mocha's meaning
(reject on a truthy argument, resolve otherwise) through a local `done`.
* test: move the spec runner's own semantics out of the mocha shim
Three things the shim did are not mocha compatibility but how the Electron
specs need to run, whichever API they are written against: every hook and
test starts from a fresh macrotask so that Chromium's message loop turns
between them, `defer()`-ed cleanup runs before the enclosing suites' own
afterEach hooks, and spec/disabled-tests.json can switch a test off by its
title. Those now live in a small custom vitest runner
(spec/vitest/runner.ts) that applies to every test, and the shim only
translates mocha's API.
* test: write the specs against vitest's API instead of mocha's
Mechanical conversion of every spec file and helper:
- `describe`/`it`/`beforeEach`/... are imported from 'vitest' rather than
taken from the runner's globals; `before`/`after` become
`beforeAll`/`afterAll`.
- `this.timeout(n)` becomes the `{ timeout: n }` option of the test or
suite (a hook's second argument; hooks inside a suite that had a timeout
get it explicitly, since vitest's suite option only reaches the tests), `this.retries(n)` `{ retry: n }`, and
`this.skip()` the test context's `ctx.skip()`. The two `before` hooks that
skipped a whole suite now compute the condition up front
(`describe.runIf`) or per test. `function () {}` callbacks that only
existed for `this` are arrows again.
- `ifit`/`ifdescribe` map to `it.skip`/`describe.skip`, mocha's chained
`it(...).timeout(n)` and `this.bail()` are gone, and the two helpers that
read `this.test` use the context's task state.
* test: remove the mocha compatibility layer
Nothing imports mocha's API any more, so spec/vitest/mocha-compat.ts and the
setup file that installed its globals go, together with @types/mocha and the
Mocha type overloads in spec/ambient.d.ts. Timeouts are vitest's own again
(30 s per test and hook, ELECTRON_SPEC_TIMEOUT raises it for the sanitizer
jobs, replacing MOCHA_TIMEOUT), the junit path variable becomes
ELECTRON_SPEC_JUNIT_FILE, and `closeAllWindows` loses the parameter that a
hook's context argument would otherwise land in.
291 lines
8.2 KiB
TypeScript
291 lines
8.2 KiB
TypeScript
import {
|
|
BaseWindow,
|
|
BrowserWindow,
|
|
type BrowserWindowConstructorOptions,
|
|
webContents,
|
|
type WebContents,
|
|
WebContentsView
|
|
} from 'electron/main';
|
|
|
|
import { afterEach, beforeAll, expect, it } from 'vitest';
|
|
|
|
import * as cp from 'node:child_process';
|
|
import { once } from 'node:events';
|
|
import * as path from 'node:path';
|
|
import { setTimeout } from 'node:timers/promises';
|
|
|
|
import { ifdescribe, waitUntil } from './lib/spec-helpers.ts';
|
|
import { closeAllWindows } from './lib/window-helpers.ts';
|
|
|
|
// visibilityState specs pass on linux with a real window manager but on CI
|
|
// the environment does not let these specs pass
|
|
ifdescribe(process.platform !== 'linux')('document.visibilityState', () => {
|
|
let w: BaseWindow & { webContents: WebContents };
|
|
|
|
beforeAll(() => {
|
|
for (const checkWin of BaseWindow.getAllWindows()) {
|
|
console.log('WINDOW EXISTS BEFORE TEST STARTED:', checkWin.title, checkWin.id);
|
|
}
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await closeAllWindows();
|
|
w = null as unknown as BrowserWindow;
|
|
const existingWCS = webContents.getAllWebContents();
|
|
existingWCS.forEach((contents) => contents.close());
|
|
});
|
|
|
|
const load = () =>
|
|
w.webContents.loadFile(path.resolve(import.meta.dirname, 'fixtures', 'chromium', 'visibilitystate.html'));
|
|
|
|
async function haveVisibilityState(state: string) {
|
|
const docVisState = await w.webContents.executeJavaScript('document.visibilityState');
|
|
return docVisState === state;
|
|
}
|
|
|
|
// On the Windows CI hosts another process's console window can end up
|
|
// above a newly shown test window, and Chromium's native occlusion tracker
|
|
// then reports the page as 'hidden'. Keep the window above everything there
|
|
// so the desktop's z-order cannot decide the outcome. macOS runs the
|
|
// occlusion specs below, which need a normal window level.
|
|
const alwaysOnTop = process.platform === 'win32';
|
|
|
|
const itWithOptions = (
|
|
name: string,
|
|
options: BrowserWindowConstructorOptions,
|
|
fn: () => unknown,
|
|
testOptions: { timeout?: number } = {}
|
|
) => {
|
|
it(name, testOptions, async () => {
|
|
w = new BrowserWindow({
|
|
alwaysOnTop,
|
|
...options,
|
|
paintWhenInitiallyHidden: false,
|
|
webPreferences: {
|
|
...(options.webPreferences || {}),
|
|
nodeIntegration: true,
|
|
contextIsolation: false
|
|
}
|
|
});
|
|
if (options.show && process.platform === 'darwin') {
|
|
await once(w, 'show');
|
|
}
|
|
await fn();
|
|
});
|
|
|
|
it(name + ' with BaseWindow', testOptions, async () => {
|
|
const baseWindow = new BaseWindow({
|
|
alwaysOnTop,
|
|
...options
|
|
});
|
|
const wcv = new WebContentsView({
|
|
webPreferences: { ...(options.webPreferences ?? {}), nodeIntegration: true, contextIsolation: false }
|
|
});
|
|
baseWindow.contentView = wcv;
|
|
w = Object.assign(baseWindow, { webContents: wcv.webContents });
|
|
if (options.show && process.platform === 'darwin') {
|
|
await once(w, 'show');
|
|
}
|
|
await fn();
|
|
});
|
|
};
|
|
|
|
itWithOptions('should be visible when the window is initially shown by default', {}, async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
});
|
|
|
|
itWithOptions(
|
|
'should be visible when the window is initially shown',
|
|
{
|
|
show: true
|
|
},
|
|
async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
}
|
|
);
|
|
|
|
itWithOptions(
|
|
'should be hidden when the window is initially hidden',
|
|
{
|
|
show: false
|
|
},
|
|
async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('hidden'));
|
|
}
|
|
);
|
|
|
|
itWithOptions(
|
|
'should be visible when the window is initially hidden but shown before the page is loaded',
|
|
{
|
|
show: false
|
|
},
|
|
async () => {
|
|
w.show();
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
}
|
|
);
|
|
|
|
itWithOptions(
|
|
'should be hidden when the window is initially shown but hidden before the page is loaded',
|
|
{
|
|
show: true
|
|
},
|
|
async () => {
|
|
w.hide();
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('hidden'));
|
|
}
|
|
);
|
|
|
|
itWithOptions('should be toggle between visible and hidden as the window is hidden and shown', {}, async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
w.hide();
|
|
await waitUntil(async () => await haveVisibilityState('hidden'));
|
|
w.show();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
});
|
|
|
|
itWithOptions('should become hidden when a window is minimized', {}, async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
w.minimize();
|
|
await waitUntil(async () => await haveVisibilityState('hidden'));
|
|
});
|
|
|
|
itWithOptions('should become visible when a window is restored', {}, async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
w.minimize();
|
|
await waitUntil(async () => await haveVisibilityState('hidden'));
|
|
w.restore();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
});
|
|
|
|
ifdescribe(process.platform === 'darwin')('on platforms that support occlusion detection', () => {
|
|
let child: cp.ChildProcess;
|
|
|
|
const makeOtherWindow = (opts: { x: number; y: number; width: number; height: number }) => {
|
|
child = cp.spawn(process.execPath, [
|
|
path.resolve(import.meta.dirname, 'fixtures', 'chromium', 'other-window.js'),
|
|
`${opts.x}`,
|
|
`${opts.y}`,
|
|
`${opts.width}`,
|
|
`${opts.height}`
|
|
]);
|
|
return new Promise<void>((resolve) => {
|
|
child.stdout!.on('data', (chunk) => {
|
|
if (chunk.toString().includes('__ready__')) resolve();
|
|
});
|
|
});
|
|
};
|
|
|
|
afterEach(() => {
|
|
if (child && !child.killed) {
|
|
child.kill('SIGTERM');
|
|
}
|
|
});
|
|
|
|
itWithOptions(
|
|
'should be visible when two windows are on screen',
|
|
{
|
|
x: 0,
|
|
y: 0,
|
|
width: 200,
|
|
height: 200
|
|
},
|
|
async () => {
|
|
await makeOtherWindow({
|
|
x: 200,
|
|
y: 0,
|
|
width: 200,
|
|
height: 200
|
|
});
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
}
|
|
);
|
|
|
|
itWithOptions(
|
|
'should be visible when two windows are on screen that overlap partially',
|
|
{
|
|
x: 50,
|
|
y: 50,
|
|
width: 150,
|
|
height: 150
|
|
},
|
|
async () => {
|
|
await makeOtherWindow({
|
|
x: 100,
|
|
y: 0,
|
|
width: 200,
|
|
height: 200
|
|
});
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
}
|
|
);
|
|
|
|
itWithOptions(
|
|
'should be hidden when a second window completely occludes the current window',
|
|
{
|
|
x: 50,
|
|
y: 50,
|
|
width: 50,
|
|
height: 50
|
|
},
|
|
async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
makeOtherWindow({
|
|
x: 0,
|
|
y: 0,
|
|
width: 300,
|
|
height: 300
|
|
});
|
|
await waitUntil(async () => await haveVisibilityState('hidden'));
|
|
},
|
|
{ timeout: 240000 }
|
|
);
|
|
|
|
// https://github.com/electron/electron/issues/51718
|
|
itWithOptions(
|
|
'should stay visible when covered by a transparent click-through overlay',
|
|
{
|
|
x: 100,
|
|
y: 100,
|
|
width: 200,
|
|
height: 200
|
|
},
|
|
async () => {
|
|
load();
|
|
await waitUntil(async () => await haveVisibilityState('visible'));
|
|
|
|
const overlay = new BrowserWindow({
|
|
x: 50,
|
|
y: 50,
|
|
width: 400,
|
|
height: 400,
|
|
show: false,
|
|
transparent: true,
|
|
frame: false,
|
|
alwaysOnTop: true,
|
|
focusable: false
|
|
});
|
|
overlay.setIgnoreMouseEvents(true);
|
|
await overlay.loadURL('about:blank');
|
|
overlay.showInactive();
|
|
|
|
// Give the occlusion checker time to run; the covered window must not
|
|
// be marked occluded by a window that can't obscure it.
|
|
await setTimeout(2000);
|
|
expect(await w.webContents.executeJavaScript('document.visibilityState')).toBe('visible');
|
|
}
|
|
);
|
|
});
|
|
});
|