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.
102 lines
3.9 KiB
TypeScript
102 lines
3.9 KiB
TypeScript
// Clicks that another process posts straight to an app with CGEventPostToPid()
|
|
// (see spec/fixtures/native-addon/mouse-input). The window server does not
|
|
// route them, so unlike a click at an event tap they do not activate the app.
|
|
// The app under test is a second Electron process, so that this one is the
|
|
// other process. Its main process logs activations and mouse downs, and there
|
|
// are no retries: a click that only sometimes gets through is a failure.
|
|
import { app } from 'electron/main';
|
|
|
|
import { afterEach, beforeAll, beforeEach, expect, it } from 'vitest';
|
|
|
|
import { once } from 'node:events';
|
|
import { createRequire } from 'node:module';
|
|
|
|
import { ifdescribe, startRemoteControlApp, waitUntil } from './lib/spec-helpers.ts';
|
|
|
|
const require = createRequire(import.meta.url);
|
|
|
|
type MouseInput = {
|
|
postClickToWindow(pid: number, windowNumber: number, x: number, y: number): unknown;
|
|
getDiagnostics(): Record<string, unknown>;
|
|
};
|
|
|
|
const BOUNDS = { x: 100, y: 100, width: 400, height: 400 };
|
|
const POINT = { x: BOUNDS.x + 200, y: BOUNDS.y + 200 };
|
|
|
|
ifdescribe(process.platform === 'darwin' && !process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)(
|
|
'clicks posted to a background app',
|
|
{ tags: ['serial'], retry: 0 },
|
|
() => {
|
|
let mouse: MouseInput;
|
|
let rc: Awaited<ReturnType<typeof startRemoteControlApp>>;
|
|
|
|
let canPostEvents = true;
|
|
beforeAll(() => {
|
|
mouse = require('@electron-ci/mouse-input');
|
|
canPostEvents = !!process.env.CI || !!mouse.getDiagnostics().postEventAccess;
|
|
});
|
|
beforeEach((ctx) => {
|
|
if (!canPostEvents) ctx.skip();
|
|
});
|
|
|
|
beforeEach(async () => {
|
|
rc = await startRemoteControlApp();
|
|
await rc.remotely(() => {
|
|
const { app } = require('electron');
|
|
const log: string[] = ((globalThis as any).log = []);
|
|
app.on('did-become-active', () => log.push('active'));
|
|
app.on('did-resign-active', () => log.push('inactive'));
|
|
});
|
|
});
|
|
|
|
afterEach(async () => {
|
|
const exited = once(rc.process, 'exit');
|
|
rc.process.kill('SIGKILL');
|
|
await exited;
|
|
});
|
|
|
|
const openWindow = (name: string, options: Electron.BrowserWindowConstructorOptions = {}): Promise<number> =>
|
|
rc.remotely(
|
|
async (name: string, options: Electron.BrowserWindowConstructorOptions) => {
|
|
const { BrowserWindow } = require('electron');
|
|
const w = new BrowserWindow({ ...options, show: false });
|
|
w.webContents.on('input-event', (_: unknown, input: Electron.InputEvent) => {
|
|
if (input.type === 'mouseDown') (globalThis as any).log.push(`mouseDown ${name}`);
|
|
});
|
|
await w.loadURL('about:blank');
|
|
w.showInactive();
|
|
return Number(w.getMediaSourceId().split(':')[1]);
|
|
},
|
|
name,
|
|
{ ...BOUNDS, frame: false, alwaysOnTop: true, ...options }
|
|
);
|
|
const log = (): Promise<string[]> => rc.remotely(() => (globalThis as any).log);
|
|
const logged = (entry: string) => waitUntil(async () => (await log()).includes(entry));
|
|
const sendToBackground = async () => {
|
|
app.focus({ steal: true });
|
|
await waitUntil(() => rc.remotely(() => !require('electron').app.isActive()));
|
|
await rc.remotely(() => {
|
|
(globalThis as any).log.length = 0;
|
|
});
|
|
};
|
|
const postClick = (windowNumber: number) =>
|
|
mouse.postClickToWindow(rc.process.pid!, windowNumber, POINT.x, POINT.y);
|
|
|
|
it('reach a window that accepts the first mouse', async () => {
|
|
const w = await openWindow('main', { acceptFirstMouse: true });
|
|
await sendToBackground();
|
|
postClick(w);
|
|
await logged('mouseDown main');
|
|
expect(await log()).toEqual(['mouseDown main']);
|
|
});
|
|
|
|
it('reach the page without activating the app', async () => {
|
|
const w = await openWindow('main');
|
|
await sendToBackground();
|
|
postClick(w);
|
|
await logged('mouseDown main');
|
|
expect(await log()).toEqual(['mouseDown main']);
|
|
});
|
|
}
|
|
);
|