首页 > 解决方案 > cypress 窗口中的站点不安全

问题描述

我们的网站是安全的,chrome 还显示“安全”锁定图标。但是当我运行 cypress 自动化测试时,cypress 窗口显示“不安全”。所以我在控制台上收到以下错误并且页面未加载。

SecurityError:不安全的 SockJS 连接可能无法从通过 HTTPS 加载的页面启动

错误图像

如何解决此问题

注意:我们有 sockJs 客户端。所以 sockjs-client 会抛出这个错误。

sockjs-client/lib/main.js:79

if (loc.protocol === 'https:' && !secure) { 
   throw new Error('SecurityError: An insecure SockJS connection may not be initiated from a page loaded over HTTPS'); 
 }  

标签: httpscypresssockjs

解决方案


如果您只想解决这个错误(而不是首先不在本地主机上抛出错误),您可以像这样将其静音。

我已经考虑到你在评论中写的内容,虽然我不知道原因,但让我们拿出大炮。如果这不起作用,那么我不知道。

这假设您正在使用cy.visit加载您的页面。此外,这不适用于非页面测试(例如,当您根本不加载页面时)。

// cypress/support/index.js

Cypress.Commands.overwrite( 'visit', (origFn, url, opts = {}) => {
  // normalize arguments
  // -------------------------------------------------------------------------
  if ( typeof url == 'string' ) {
    opts.url = url;
  } else {
    opts = url;
  }

  // overwrite onBeforeLoad
  // -------------------------------------------------------------------------
  const _onBeforeLoad = opts.onBeforeLoad;
  opts.onBeforeLoad = function ( win ) {

    // monkey-patch `window.onerror` callback which Cypress uses for error
    //  handling. When cypress starts to use `addEventListener`, then we're
    //  in trouble.
    // Note: By this time, Cypress should have added the callback. If this
    //  wasn't the case, we'd have to add a setter on `window.onerror` and
    //  ensure we wrap the callback, there.
    const _onerror = win.onerror;
    win.onerror = function ( err ) {
      if (
        typeof err === 'string' &&
        err.includes('SecurityError: An insecure SockJS')
      ) return;

      _onerror.call(win, ...arguments);
    }
    // add a regular listener in order to prevent logging to devTools console
    win.addEventListener('error', ev => {
      if (
        ev && typeof ev.message === 'string' &&
        ev.message.includes('SecurityError: An insecure SockJS')
      ) {
        ev.preventDefault();
        ev.stopImmediatePropagation();
      }
    });

    // call user-supplied `onBeforeLoad` callback, if supplied
    if ( _onBeforeLoad ) _onBeforeLoad(win);
  }
  // -------------------------------------------------------------------------
  return origFn(opts);
});

另请参阅关闭所有未捕获的异常处理


推荐阅读