You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress端测遇NotSupportedError:Chrome等浏览器适配方案问询

解决Cypress中Chrome/Chromium/Electron环境下PasswordCredential的NotSupportedError问题

一、抑制未捕获异常的Cypress配置

可以通过Cypress的uncaught:exception事件过滤特定错误,避免测试失败。在cypress.config.js(或cypress.config.ts)中添加如下配置:

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('uncaught:exception', (err, runnable) => {
        // 过滤目标错误,阻止Cypress标记为测试失败
        if (err.message.includes('NotSupportedError: The user agent does not support public key credentials')) {
          return false;
        }
        // 其他异常保持默认处理逻辑
        return true;
      });
    },
  },
});

二、Stub PasswordCredential功能(适配不支持的浏览器)

由于Cypress环境下Chrome类浏览器对Web Credentials API存在支持限制,可通过全局或局部Stub模拟API行为:

1. 全局Stub(所有测试生效)

在cypress/support/e2e.js(或e2e.ts)中添加代码,在页面加载前覆盖API:

Cypress.on('window:before:load', (win) => {
  // 模拟PasswordCredential构造函数
  win.PasswordCredential = class PasswordCredential {
    constructor(options) {
      this.id = options.id;
      this.password = options.password;
      this.name = options.name;
    }
  };

  // 模拟凭证存储方法,返回成功Promise
  win.navigator.credentials.store = () => Promise.resolve(true);
});

2. 局部Stub(单个测试用例生效)

若仅需在特定测试中Stub,可在测试内通过cy.window()操作:

it('测试登录流程', () => {
  cy.visit('/login');
  
  cy.window().then((win) => {
    win.PasswordCredential = class PasswordCredential {
      constructor(options) {
        this.id = options.id;
        this.password = options.password;
        this.name = options.name;
      }
    };

    // 用Stub替代存储方法,可验证调用情况
    win.navigator.credentials.store = cy.stub().resolves(true);
  });

  // 执行登录操作...
});

三、补充说明

你的现有代码已做window.PasswordCredential的存在性判断,但问题出在navigator.credentials.store调用时抛出异常,因此需要同时Stub存储方法。升级Node版本或superagent无法解决此问题,本质是Cypress测试环境下Chrome类浏览器的安全策略限制导致API不可用。

内容的提问来源于stack exchange,提问作者Mithun Shreevatsa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 20:50:16