Skip to content

Instantly share code, notes, and snippets.

@myobie

myobie/runner.ts

Created Jan 26, 2021
Embed
What would you like to do?
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