Webdriverio - 如何检测浏览器 window 是否关闭

Webdriverio - How to detect a browser window being closed

我正在使用 webdriverio 和 mocha 进行自动化测试。如果在执行我的自动化测试时浏览器 window 关闭,我想结束该过程而不是继续执行我的测试。有没有办法检测浏览器关闭?我在 selenium 日志中看到了信息,但我不知道如何在我的实际节点脚本中检测到它。这是 selenium 服务器日志中的错误:

12:33:17.122 警告 - 抛出异常 org.openqa.selenium.NoSuchWindowException: Window 未找到。浏览器 window 可能已关闭。

您可以使用 client.sessions() 检查会话是否仍然存在。你可以使用这个

describe('check if session still exist', function() {

    it('should check if session still exist', function() {
    return browser.sessions().then(function(sessionid){
    var id1 = sessionid
    console.log(id1);
      });
   });
});

如果没有会话,上面将 return

{ state: 'success',
  sessionId: null,
  hCode: 1944289324,
  value: [],
  class: 'org.openqa.selenium.remote.Response',
  status: 0 }

否则它会return像这样

 state: 'success',
  sessionId: null,
  hCode: 381733075,
  value:

   [ { capabilities: [Object],
       id: '8ec2e2e8-6833-4105-8b84-1a6ce74a29ff',
       hCode: 1337873045,
       class: 'org.openqa.selenium.remote.server.handler.GetAllSessions$SessionInfo' } ],
  class: 'org.openqa.selenium.remote.Response',
  status: 0 }

然后根据上述 value json 对象,在代码的正确位置,您可以选择结束进程。