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 @@ -21,6 +21,11 @@ export interface IframeViewportDoneEvent {
iframeId: string
}

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

export interface GlobalChannelTestRunCanceledEvent {
type: 'cancel'
reason: CancelReason
Expand Down Expand Up @@ -50,6 +55,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 { BrowserTesterOptions, SerializedConfig } from 'vitest'
import type { FileSpecification } from 'vitest/internal/browser'
import { channel, client, globalChannel } from '@vitest/browser/client'
Expand All @@ -16,6 +16,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 @@ -189,8 +192,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)
}

await this.prepareIframe(
Expand Down Expand Up @@ -253,12 +255,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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where the actual bug-fix is. Instead of just assuming we can this.sendEventToIframe({ event: 'prepare', ... }) we now wait until the <iframe> has told us it is ready.

.then(() => this.sendEventToIframe({
event: 'prepare',
iframeId,
startTime,
otelCarrier: this.traces.getContextCarrier(otelContext),
}))
.then(resolve, error => reject(this.dispatchIframeError(error)))
}
}
iframe.onerror = (e) => {
Expand All @@ -276,6 +280,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 @@ -365,9 +397,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 @@ -114,6 +114,11 @@ getBrowserState().iframeId = iframeId

registerPageMarkHandler((name, options) => page.mark(name, options))

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