Skip to content

Commit 89046a6

Browse files
committed
fix(webdriverio): allow switchWindow with no current window
1 parent 76fd3cb commit 89046a6

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

packages/webdriverio/src/commands/browser/switchWindow.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,13 @@ export async function switchWindow (
4646
}
4747

4848
const currentWindow = await this.getWindowHandle()
49+
/**
50+
* in cases where a browser window was closed by e.g. clicking on a button
51+
* this command may throws an "no such window: target window already closed"
52+
* error. In this case we return `undefined` and determine the new window
53+
* based on the command parameter.
54+
*/
55+
.catch(() => undefined)
4956

5057
// is the matcher a window handle, and are we in the right window already?
5158
if (typeof matcher === 'string' && currentWindow === matcher) {

packages/webdriverio/tests/commands/browser/switchWindow.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,15 @@ describe('switchWindow', () => {
105105
expect(tabId).toBe('window-handle-1')
106106
})
107107

108+
it('should allow switchWindow call even when the currently active one is closed', async () => {
109+
vi.spyOn(browser, 'getWindowHandle').mockImplementation(() =>
110+
Promise.reject('target window already closed')
111+
)
112+
113+
const tabId = await browser.switchWindow('webdriver.io')
114+
expect(tabId).toBe('window-handle-1')
115+
})
116+
108117
afterAll(() => {
109118
// @ts-expect-error
110119
delete global.window

0 commit comments

Comments
 (0)