Skip to content

Instantly share code, notes, and snippets.

@myobie
Created January 26, 2021 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myobie/7df49af6f1d506a06b98571a1d3f5259 to your computer and use it in GitHub Desktop.
Save myobie/7df49af6f1d506a06b98571a1d3f5259 to your computer and use it in GitHub Desktop.
const worker = new Worker('/tests.js')
worker.onmessage = e => {
if (e.data && e.data._command) {
if (e.data._command === 'console') {
const type = e.data.type || 'log'
const msg = e.data.msg || '<empty>'
switch (type) {
case 'error':
console.error(msg)
break
case 'debug':
console.debug(msg)
break
default:
console.log(msg)
}
}
if (e.data._command === 'synthetic') {
const data = e.data.data
worker.postMessage(data)
}
} else {
worker.postMessage({
_command: 'parentReceived',
receivedData: e.data
})
}
}
worker.postMessage({ _command: 'run' })
import { run } from '@shareup/zora-test-harness'
export { test } from '@shareup/zora-test-harness'
type Data = Record<string, unknown>
type Listener = (data: Data) => void
type Matcher = (data: Data) => boolean
const listeners: Set<Listener> = new Set()
self.addEventListener('message', (e: MessageEvent) => {
if (e.data && e.data._command) {
if (e.data._command === 'run') {
console.log('# ** running tests inside Worker')
run()
return
}
if (e.data._command === 'parentReceived') {
for (const cb of listeners) {
cb(e.data)
}
}
}
})
// NOTE: forward console messages
self.console.debug = (...msg: unknown[]) => { postConsole('debug', msg) }
self.console.error = (...msg: unknown[]) => { postConsole('error', msg) }
self.console.log = (...msg: unknown[]) => { postConsole('log', msg) }
function postConsole (type: 'debug' | 'error' | 'log', msg: unknown) {
if (Array.isArray(msg) && msg.length === 1) {
msg = msg[0]
}
if (typeof msg !== 'string') {
msg = JSON.stringify(msg)
}
self.postMessage({ _command: 'console', type, msg })
}
export function postMessageFromParent (data: Record<string, unknown>): void {
self.postMessage({ _command: 'synthetic', data })
}
export function nextReceivedByParent (possibleMatcher: Matcher | undefined): Promise<Data> {
const matcher = possibleMatcher || (() => true)
return new Promise<Data>(resolve => {
const listener: Listener = data => {
if (matcher(data)) {
resolve(data)
deleteParentListener(listener)
}
}
addParentListener(listener)
})
}
export function addParentListener (listener: Listener): void {
listeners.add(listener)
}
export function deleteParentListener (listener: Listener): void {
listeners.delete(listener)
}
export function deleteAllParentListeners (): void {
listeners.forEach(deleteParentListener)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment