Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(): Update canvas and jsdom #10417

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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 .github/actions/cached-install/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ runs:
steps:
- name: Install system deps for node canvas
if: inputs.install-system-deps == 'true'
run: sudo apt-get install libgif-dev libpng-dev libpango1.0-dev libjpeg8-dev librsvg2-dev libcairo2-dev
run: sudo apt-get install libgif-dev libpng-dev libpango1.0-dev libjpeg-dev librsvg2-dev libcairo2-dev
shell: bash
- name: Use Node.js v${{ inputs.node-version }}
uses: actions/setup-node@v4
Expand Down
207 changes: 207 additions & 0 deletions jest-env/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import type { Context } from 'vm';
import type * as jsdom from 'jsdom';
import * as JSDOM from 'jsdom';
import type {
EnvironmentContext,
JestEnvironment,
JestEnvironmentConfig,
} from '@jest/environment';
import { LegacyFakeTimers, ModernFakeTimers } from '@jest/fake-timers';
import type { Global } from '@jest/types';
import { ModuleMocker } from 'jest-mock';
import { installCommonGlobals } from 'jest-util';

// The `Window` interface does not have an `Error.stackTraceLimit` property, but
Copy link

@Smrtnyk Smrtnyk Jan 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you considered on moving to vitest for unit tests and executing tests in real browser?
that way you can use real canvas for testing and not fake jsdom one
https://vitest.dev/guide/browser/
vitest has jest compatible API so I guess it wouldn't be that much work migrating unit tests

btw jest isn't seeing much love lately, it is barely maintained and I am questioning its future to be honest

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue is that 70% of our unit tests are still on QUnit.
Then we have playwright.
Ideally unit tests won't run in the browser and will just test the fabricJS code and not require a real canvas, but just a mocked one.
Visual tests will run both in the browser and node throught playwright and would be based on browser or JSDOM + canvas and test also output of the canvas.

Vitest should be api compatibile with jest, and easy replacement, but before doing anything like that i would like to see qunit replaced.

So what we have now is a middle ground because there is no firepower to rewrite all the unit tests

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be clear if you want to open a PR to swap jest with vitest and and have it running in node only for now, you are welcome to do so, as long as it can support canvas with JSDOM is all good

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be clear if you want to open a PR to swap jest with vitest and and have it running in node only for now, you are welcome to do so, as long as it can support canvas with JSDOM is all good

I am interested in this so will have a look at this on the weekend

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hm, vitest also requires minimum support of node18
I have all tests running now in vitest, but I had to up node to 18
but with this you don't need this all ceremony with custom environment
with vitest you just install jsdom 26 and canvas v3 and tests just work

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@asturur I have create a draft PR #10420
all tests are working for me locally in vitest now
maybe you would want to merge it with this branch?
in there I am using newest jsdom and canvas v3 and this acrobatics with custom environment should not be needed

// `JSDOMEnvironment` assumes it is there.
type Win = Window &
Global.Global & {
Error: {
stackTraceLimit: number;
};
};

function isString(value: unknown): value is string {
return typeof value === 'string';
}

export abstract class BaseJSDOMEnvironment implements JestEnvironment<number> {
dom: jsdom.JSDOM | null;
fakeTimers: LegacyFakeTimers<number> | null;
fakeTimersModern: ModernFakeTimers | null;
global: Win;
private errorEventListener:
| ((event: Event & { error: Error }) => void)
| null;
moduleMocker: ModuleMocker | null;
customExportConditions = ['browser'];
private readonly _configuredExportConditions?: Array<string>;

protected constructor(
config: JestEnvironmentConfig,
context: EnvironmentContext,
jsdomModule: typeof jsdom,
) {
const { projectConfig } = config;

const { JSDOM, ResourceLoader, VirtualConsole } = jsdomModule;

const virtualConsole = new VirtualConsole();
virtualConsole.sendTo(context.console, { omitJSDOMErrors: true });
virtualConsole.on('jsdomError', (error) => {
context.console.error(error);
});

this.dom = new JSDOM(
typeof projectConfig.testEnvironmentOptions.html === 'string'
? projectConfig.testEnvironmentOptions.html
: '<!DOCTYPE html>',
{
pretendToBeVisual: true,
resources:
typeof projectConfig.testEnvironmentOptions.userAgent === 'string'
? new ResourceLoader({
userAgent: projectConfig.testEnvironmentOptions.userAgent,
})
: undefined,
runScripts: 'dangerously',
url: 'http://localhost/',
virtualConsole,
...projectConfig.testEnvironmentOptions,
},
);
const global = (this.global = this.dom.window as unknown as Win);

if (global == null) {
throw new Error('JSDOM did not return a Window object');
}

// TODO: remove at some point - for "universal" code (code should use `globalThis`)
global.global = global;

// Node's error-message stack size is limited at 10, but it's pretty useful
// to see more than that when a test fails.
this.global.Error.stackTraceLimit = 100;
installCommonGlobals(global, projectConfig.globals);

// TODO: remove this ASAP, but it currently causes tests to run really slow
global.Buffer = Buffer;

// Report uncaught errors.
this.errorEventListener = (event) => {
if (userErrorListenerCount === 0 && event.error != null) {
process.emit('uncaughtException', event.error);
}
};
global.addEventListener('error', this.errorEventListener);

// However, don't report them as uncaught if the user listens to 'error' event.
// In that case, we assume the might have custom error handling logic.
const originalAddListener = global.addEventListener.bind(global);
const originalRemoveListener = global.removeEventListener.bind(global);
let userErrorListenerCount = 0;
global.addEventListener = function (
...args: Parameters<typeof originalAddListener>
) {
if (args[0] === 'error') {
userErrorListenerCount++;
}
return originalAddListener.apply(this, args);
};
global.removeEventListener = function (
...args: Parameters<typeof originalRemoveListener>
) {
if (args[0] === 'error') {
userErrorListenerCount--;
}
return originalRemoveListener.apply(this, args);
};

if ('customExportConditions' in projectConfig.testEnvironmentOptions) {
const { customExportConditions } = projectConfig.testEnvironmentOptions;
if (
Array.isArray(customExportConditions) &&
customExportConditions.every(isString)
) {
this._configuredExportConditions = customExportConditions;
} else {
throw new Error(
'Custom export conditions specified but they are not an array of strings',
);
}
}

this.moduleMocker = new ModuleMocker(global);

this.fakeTimers = new LegacyFakeTimers({
config: projectConfig,
global: global as unknown as typeof globalThis,
moduleMocker: this.moduleMocker,
timerConfig: {
idToRef: (id: number) => id,
refToId: (ref: number) => ref,
},
});

this.fakeTimersModern = new ModernFakeTimers({
config: projectConfig,
global: global as unknown as typeof globalThis,
});
}

// eslint-disable-next-line @typescript-eslint/no-empty-function
async setup(): Promise<void> {}

async teardown(): Promise<void> {
if (this.fakeTimers) {
this.fakeTimers.dispose();
}
if (this.fakeTimersModern) {
this.fakeTimersModern.dispose();
}
if (this.global != null) {
if (this.errorEventListener) {
this.global.removeEventListener('error', this.errorEventListener);
}
this.global.close();
}
this.errorEventListener = null;
// @ts-expect-error: this.global not allowed to be `null`
this.global = null;
this.dom = null;
this.fakeTimers = null;
this.fakeTimersModern = null;
}

exportConditions(): Array<string> {
return this._configuredExportConditions ?? this.customExportConditions;
}

getVmContext(): Context | null {
if (this.dom) {
return this.dom.getInternalVMContext();
}
return null;
}
}

export default class JSDOMEnvironment extends BaseJSDOMEnvironment {
constructor(config: JestEnvironmentConfig, context: EnvironmentContext) {
super(config, context, JSDOM);
}
}

export const TestEnvironment = JSDOMEnvironment;
2 changes: 1 addition & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ module.exports = {
// snapshotSerializers: [],

// The test environment that will be used for testing
testEnvironment: 'jsdom',
testEnvironment: './jest-env/index.ts',

// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
Expand Down
Loading
Loading