Skip to content

Module workers make tests fail due to Hammerhead injecting a call to 'importScripts' #3053

@thomas-jakemeyn

Description

@thomas-jakemeyn

What is your Scenario?

My application code creates module workers as follows (see spec here):

const worker = new Worker("worker.js", { type: "module" });

What is the Current behavior?

testcafe-hammerhead injects some code in the worker. That code calls the function importScripts() if it is available in the global context (see here).

The problem is that, in the context of a module worker, the function importScripts() is available but it throws a TypeError (see spec here), which makes tests fail.

Failed to execute 'importScripts' on 'WorkerGlobalScope': Module scripts don't support importScripts().

As a workaround, I have currently patched testcafe-hammerhead to check the type of the worker before calling importScripts(). For a module worker, self.type is not classic but module (see spec here).

diff --git a/node_modules/testcafe-hammerhead/lib/processing/script/header.js b/node_modules/testcafe-hammerhead/lib/processing/script/header.js
index ff7b1f7..91da97c 100644
--- a/node_modules/testcafe-hammerhead/lib/processing/script/header.js
+++ b/node_modules/testcafe-hammerhead/lib/processing/script/header.js
@@ -20,7 +20,7 @@ const STRICT_MODE_PLACEHOLDER = '{strict-placeholder}';
 const SW_SCOPE_HEADER_VALUE = '{sw-scope-header-value}';
 const WORKER_SETTINGS_PLACEHOLDER = '{worker-settings}';
 const IMPORT_WORKER_HAMMERHEAD = `
-if (typeof importScripts !== "undefined" && /\\[native code]/g.test(importScripts.toString())) {
+if (self?.type === 'classic' && typeof importScripts !== "undefined" && /\\[native code]/g.test(importScripts.toString())) {
     var ${instruction_1.default.getWorkerSettings} = function () {return ${WORKER_SETTINGS_PLACEHOLDER}};
     importScripts((location.origin || (location.protocol + "//" + location.host)) + "${service_routes_1.default.workerHammerhead}");
 }

What is the Expected behavior?

testcafe-hammerhead should properly support module workers.

What is your public website URL? (or attach your complete example)

NA

What is your TestCafe test code?

NA

Your complete configuration file

No response

Your complete test report

No response

Screenshots

No response

Steps to Reproduce

NA

TestCafe version

3.7.2

Node.js version

No response

Command-line arguments

NA

Browser name(s) and version(s)

No response

Platform(s) and version(s)

No response

Other

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions