Last active
July 4, 2022 20:30
-
-
Save dfkaye/4f368f446cb1efc06fb0c764f0e8a4f6 to your computer and use it in GitHub Desktop.
testing worker functions independently ~ prior to parsing and embedding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 27 june 2022 | |
// testing workers functions independently ~ prior to parsing and embedding | |
// yet one more step in the quest for making embedded workers testable | |
// from the console... | |
// ...continued from "communicating embedded web workers" | |
// at https://gist.github.com/dfkaye/c6d77fde86aea70ef6ae79bda2219582 | |
// demonstrates how to *test* one or more worker script functions **as standalone functions** outside the worker context. | |
// This may be a bad or (worse) useless idea... | |
// Main concept, this function accepts a subject function with a single "self" parameter, | |
// plus an optional "self" options object to be passe to the subject function. | |
function Test(fn, self) { | |
self = Object(self); | |
typeof self.postMessage == "function" || ( | |
Object.assign(self, { | |
postMessage: console.log.bind(console) | |
}) | |
); | |
fn(self); | |
return self; | |
} | |
function onmessage(self) { | |
self.onmessage = function (request) { | |
var data = Object(request.data); | |
console.warn(data.sender, data.address, data.action, data.value); | |
var response = Object.assign({}, data); | |
self.postMessage(response); | |
} | |
} | |
var test = Test(onmessage); | |
// exercise onmessage directly | |
test.onmessage({ data: { | |
sender: "me", | |
address: "you", | |
action: "log", | |
value: "hello" | |
}}); | |
// me you log hello | |
// Object { sender: "me", address: "you", action: "log", value: "hello" } | |
// override the default logging version of postMessage in the "self" options object... | |
var mocked = Test(onmessage, { | |
postMessage: function (response) { | |
console.log( | |
response.address, "posting", response.value, | |
"to", response.sender, | |
response | |
); | |
} | |
}); | |
mocked.onmessage({ data: { | |
sender: "mocker", | |
address: "mocked", | |
action: "test", | |
value: "message" | |
}}); | |
// mocked posting message to mocker | |
// Object { sender: "mocker", address: "mocked", action: "test", value: "message" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note on the
Test()
function4 July 2022.
The
Test()
function uses theObject()
constructor fix rather than default assignment on theself
parameter if it's missing or undefined.The default assignment fails when
self
is a primitive (because we don't store the result ofObject.assign()
, assuming self is already an object, whereasObject()
creates a wrapped primitive.Here's a comparison of the strategies...