Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions packages/browser/src/client/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ export interface IframeViewportDoneEvent {
iframeId: string
}

export interface IframeReadyEvent {
event: 'ready'
iframeId: string
}

export interface GlobalChannelTestRunCanceledEvent {
type: 'cancel'
reason: CancelReason
Expand Down Expand Up @@ -49,6 +54,7 @@ export type GlobalChannelIncomingEvent = GlobalChannelTestRunCanceledEvent

export type IframeChannelIncomingEvent
= | IframeViewportEvent
| IframeReadyEvent

export type IframeChannelOutgoingEvent
= | IframeExecuteEvent
Expand Down
60 changes: 48 additions & 12 deletions packages/browser/src/client/orchestrator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Context as OTELContext } from '@opentelemetry/api'
import type { GlobalChannelIncomingEvent, IframeChannelIncomingEvent, IframeChannelOutgoingEvent, IframeViewportDoneEvent, IframeViewportFailEvent } from '@vitest/browser/client'
import type { GlobalChannelIncomingEvent, IframeChannelEvent, IframeChannelOutgoingEvent, IframeViewportDoneEvent, IframeViewportFailEvent } from '@vitest/browser/client'
import type { FileSpecification } from '@vitest/runner'
import type { BrowserTesterOptions, SerializedConfig } from 'vitest'
import { channel, client, globalChannel } from '@vitest/browser/client'
Expand All @@ -15,6 +15,8 @@ export class IframeOrchestrator {
private cancelled = false
private recreateNonIsolatedIframe = false
private iframes = new Map<string, HTMLIFrameElement>()
private readyIframes = new Set<string>()
private readyWaiters = new Map<string, () => void>()

public eventTarget: EventTarget = new EventTarget()

Expand Down Expand Up @@ -91,6 +93,8 @@ export class IframeOrchestrator {

this.iframes.forEach(iframe => iframe.remove())
this.iframes.clear()
this.readyIframes.clear()
this.readyWaiters.clear()

for (let i = 0; i < options.files.length; i++) {
if (this.cancelled) {
Expand Down Expand Up @@ -149,8 +153,7 @@ export class IframeOrchestrator {
// because we called "cleanup" in the previous run
// the iframe is not removed immediately to let the user see the last test
this.recreateNonIsolatedIframe = false
this.iframes.get(ID_ALL)!.remove()
this.iframes.delete(ID_ALL)
this.removeIframe(ID_ALL)
debug('recreate non-isolated iframe')
}

Expand Down Expand Up @@ -190,8 +193,7 @@ export class IframeOrchestrator {
const file = spec.filepath

if (this.iframes.has(file)) {
this.iframes.get(file)!.remove()
this.iframes.delete(file)
this.removeIframe(file)
}

const iframe = await this.prepareIframe(
Expand Down Expand Up @@ -254,12 +256,14 @@ export class IframeOrchestrator {
}
else {
this.iframes.set(iframeId, iframe)
this.sendEventToIframe({
event: 'prepare',
iframeId,
startTime,
otelCarrier: this.traces.getContextCarrier(otelContext),
}).then(resolve, error => reject(this.dispatchIframeError(error)))
this.waitForReady(iframeId)
.then(() => this.sendEventToIframe({
event: 'prepare',
iframeId,
startTime,
otelCarrier: this.traces.getContextCarrier(otelContext),
}))
.then(resolve, error => reject(this.dispatchIframeError(error)))
}
}
iframe.onerror = (e) => {
Expand All @@ -277,6 +281,34 @@ export class IframeOrchestrator {
return iframe
}

private markReady(iframeId: string) {
this.readyIframes.add(iframeId)

const waiter = this.readyWaiters.get(iframeId)
if (waiter) {
this.readyWaiters.delete(iframeId)
waiter()
}
}

private waitForReady(iframeId: string): Promise<void> {
if (this.readyIframes.has(iframeId)) {
return Promise.resolve()
}

return new Promise((resolve) => {
this.readyWaiters.set(iframeId, resolve)
})
}

private removeIframe(iframeId: string) {
const iframe = this.iframes.get(iframeId)
this.iframes.delete(iframeId)
this.readyIframes.delete(iframeId)
this.readyWaiters.delete(iframeId)
iframe?.remove()
}

private loggedIframe = new WeakSet<HTMLIFrameElement>()

private createWarningMessage(iframeId: string, location: string) {
Expand Down Expand Up @@ -342,9 +374,13 @@ export class IframeOrchestrator {
}
}

private async onIframeEvent(e: MessageEvent<IframeChannelIncomingEvent>) {
private async onIframeEvent(e: MessageEvent<IframeChannelEvent>) {
debug('iframe event', JSON.stringify(e.data))
switch (e.data.event) {
case 'ready': {
this.markReady(e.data.iframeId)
break
}
case 'viewport': {
const { width, height, iframeId: id } = e.data
const iframe = this.iframes.get(id)
Expand Down
5 changes: 5 additions & 0 deletions packages/browser/src/client/tester/tester.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ getBrowserState().commands = commands
getBrowserState().activeTraceTaskIds = new Set()
getBrowserState().iframeId = iframeId

channel.postMessage({
event: 'ready',
iframeId,
})

let contextSwitched = false

async function prepareTestEnvironment(options: PrepareOptions) {
Expand Down
60 changes: 60 additions & 0 deletions test/browser/specs/readiness.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { expect, test } from 'vitest'
import { instances, runInlineBrowserTests } from './utils'

test('prepare waits until the tester can receive browser channel events', { timeout: 5000 }, async () => {
const { stderr, testTree } = await runInlineBrowserTests(
{
'basic.test.ts': `
import { expect, test } from 'vitest'

test('runs in the browser', () => {
expect(1).toBe(1)
})
`,
'delayed-tester.html': `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Delayed Tester</title>
<script>
const addEventListener = BroadcastChannel.prototype.addEventListener
const postMessage = BroadcastChannel.prototype.postMessage
BroadcastChannel.prototype.addEventListener = function(type, listener, options) {
if (type === 'message') {
setTimeout(() => addEventListener.call(this, type, listener, options), 100)
return
}
return addEventListener.call(this, type, listener, options)
}
BroadcastChannel.prototype.postMessage = function(message) {
if (message && message.event === 'ready') {
setTimeout(() => postMessage.call(this, message), 150)
return
}
return postMessage.call(this, message)
}
</script>
</head>
<body></body>
</html>
`,
},
{
browser: {
instances: [instances[0]],
testerHtmlPath: './delayed-tester.html',
},
},
)

expect(stderr).toBe('')
expect(testTree()).toMatchInlineSnapshot(`
{
"basic.test.ts": {
"runs in the browser": "passed",
},
}
`)
})
Loading