Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/pr-413.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@wdio/browserstack-service": patch
---

- Fixed a test being reported as timed out in Test Reporting & Analytics when it reloads the session mid-test and the `afterTest` hook writes console output.
21 changes: 15 additions & 6 deletions packages/browserstack-service/src/cli/modules/testHubModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ export default class TestHubModule extends BaseModule {

Object.values(TestFrameworkState).forEach(state => {
Object.values(HookState).forEach(hook => {
TestFramework.registerObserver(state, hook, this.onAllTestEvents.bind(this))
// Pass the event's own state: observers run one after another, and an earlier
// one that awaits (e.g. the Automate session rename after a mid-test reload) lets
// concurrent LOG events overwrite the instance's current state before this runs.
TestFramework.registerObserver(state, hook, (args: Record<string, unknown>) => this.onAllTestEvents(args, state, hook))
})
})
}
Expand All @@ -89,11 +92,14 @@ export default class TestHubModule extends BaseModule {
this.sendTestSessionEvent(args)
}

onAllTestEvents(args: Record<string, unknown>) {
onAllTestEvents(args: Record<string, unknown>, dispatchedTestState?: State, dispatchedHookState?: State) {
this.logger.debug('onAllTestEvents: Called after all test events from cli configured module!!!')
const instance = args.instance as TestFrameworkInstance
const testState = instance.getCurrentTestState()
const hookState = instance.getCurrentHookState()
// The instance's current state is shared and moves with every tracked event, so prefer
// the state this observer was dispatched for. Otherwise a TEST/POST that reaches this
// observer after a LOG/POST landed is handled as a log and its finish is never sent.
const testState = dispatchedTestState ?? instance.getCurrentTestState()
const hookState = dispatchedHookState ?? instance.getCurrentHookState()
const keyTestDeferred = TestFramework.getState(instance, TestFrameworkConstants.KEY_TEST_DEFERRED)

// A NEW test is starting (INIT_TEST minted a fresh instance) — the previous test's
Expand Down Expand Up @@ -126,7 +132,7 @@ export default class TestHubModule extends BaseModule {
) {
// Create a modified args object with updated test framework state
instance.setCurrentTestState(TestFrameworkState.TEST)
this.onAllTestEvents(args)
this.onAllTestEvents(args, TestFrameworkState.TEST, hookState)
}

if (testState === TestFrameworkState.TEST || CLIUtils.matchHookRegex(testState.toString().split('.')[1])) {
Expand Down Expand Up @@ -154,7 +160,10 @@ export default class TestHubModule extends BaseModule {
this.pendingTestFinishes.set(deferUuid, { args, uuid: deferUuid })
this.logger.debug(`onAllTestEvents: deferred TEST/POST send past the after-each hook window (uuid=${deferUuid}, pending=${this.pendingTestFinishes.size})`)
} else {
this.sendTestFrameworkEvent(args)
this.sendTestFrameworkEvent(args, {
testFrameworkState: testState.toString().split('.')[1],
testHookState: hookState.toString().split('.')[1]
})
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,78 @@ describe('TestHubModule — finish held until the TEST/POST observers end (cucum
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledWith(expect.objectContaining({ uuid: 's3' }))
})
})

describe('TestHubModule — finish uses the dispatched state, not the shared instance state', () => {
let testHubModule: TestHubModule
let mockGrpcClient: { testFrameworkEvent: ReturnType<typeof vi.fn>, logCreatedEvent: ReturnType<typeof vi.fn> }

// A mocha test whose instance was moved to LOG/POST by console output from the user's
// afterTest while an earlier TEST/POST observer (the Automate session rename after a
// mid-test reload) was still awaiting.
function makeInstanceOverwrittenByLog(uuid: string) {
return {
...makeMochaTestInstance(uuid),
getCurrentTestState: () => TestFrameworkState.LOG,
getCurrentHookState: () => HookState.POST
}
}

function registeredObserver(state: unknown, hook: unknown) {
const call = vi.mocked(TestFramework.registerObserver).mock.calls.find(([s, h]) => s === state && h === hook)
return call?.[2] as (args: Record<string, unknown>) => void
}

beforeEach(() => {
vi.clearAllMocks()
process.env.WDIO_WORKER_ID = '0-1'
mockGrpcClient = {
testFrameworkEvent: vi.fn().mockResolvedValue({ success: true }),
logCreatedEvent: vi.fn().mockResolvedValue({ success: true })
}
vi.mocked(GrpcClient.getInstance).mockReturnValue(mockGrpcClient as never)
vi.mocked(TestFramework.hasState).mockReturnValue(true)
vi.mocked(TestFramework.getState).mockImplementation((instance: any, key: unknown) => {
if (key === TestFrameworkConstants.KEY_TEST_FRAMEWORK_NAME) {
return 'WebdriverIO-mocha'
}
if (key === TestFrameworkConstants.KEY_TEST_DEFERRED) {
return false
}
if (key === TestFrameworkConstants.KEY_TEST_UUID) {
return instance?.__uuid
}
return ''
})
testHubModule = new TestHubModule({ enabled: true, hubUrl: 'https://hub.browserstack.com' })
Object.defineProperty(testHubModule, 'config', {
value: { hubUrl: 'https://hub.browserstack.com' },
writable: true
})
})

afterEach(() => {
vi.resetAllMocks()
delete process.env.WDIO_WORKER_ID
})

it('queues and sends the finish when a LOG event overwrote the instance state first', async () => {
const observer = registeredObserver(TestFrameworkState.TEST, HookState.POST)
expect(observer).toBeTypeOf('function')

observer({ instance: makeInstanceOverwrittenByLog('reload'), test: { title: 'reload' } as Frameworks.Test })
await testHubModule.flushPendingTestFinishEvent()

expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledTimes(1)
expect(mockGrpcClient.testFrameworkEvent).toHaveBeenCalledWith(
expect.objectContaining({ testFrameworkState: 'TEST', testHookState: 'POST', uuid: 'reload' })
)
})

it('still handles a LOG/POST dispatch as a log', () => {
const observer = registeredObserver(TestFrameworkState.LOG, HookState.POST)
observer({ instance: makeInstanceOverwrittenByLog('log'), test: { title: 'log' } as Frameworks.Test })

expect(testHubModule.flushPendingTestFinishEvent()).toBeUndefined()
expect(mockGrpcClient.testFrameworkEvent).not.toHaveBeenCalled()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ describe('TestHubModule', () => {

await testHubModule.onAllTestEvents(mockArgs)

expect(sendTestFrameworkEventSpy).toHaveBeenCalledWith(mockArgs)
expect(sendTestFrameworkEventSpy).toHaveBeenCalledWith(mockArgs, { testFrameworkState: 'TEST', testHookState: 'PRE' })
})
})

Expand Down
Loading