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

如何在Cypress端到端测试中Mock或绕过Navigator.credentials认证

Cypress中Mock Navigator.credentials认证弹窗及过审方案

Mock Navigator.credentials触发的认证弹窗

在测试的前置操作里,直接重写浏览器的window.navigator.credentials对象,模拟它的get方法——这个方法就是触发弹窗的核心:

  • 模拟用户拒绝弹窗的情况:
beforeEach(() => {
  cy.visit('/', {
    onBeforeLoad: (win) => {
      win.navigator.credentials = {
        get: () => Promise.resolve(null)
      };
    }
  });
});
  • 模拟用户选择账号完成认证的情况:
beforeEach(() => {
  cy.visit('/', {
    onBeforeLoad: (win) => {
      win.navigator.credentials = {
        get: () => Promise.resolve({
          id: 'test-user-001',
          type: 'password',
          password: 'test-pass-123'
        })
      };
    }
  });
});

测试中通过认证环节的两种思路

思路一:Mock认证返回值

上面的第二种Mock写法,直接返回模拟的凭证对象后,应用会自动读取这个信息走登录流程,不需要手动操作弹窗,就能直接进入后续页面。

思路二:拦截后端验证请求

如果应用拿到凭证后会调用后端接口做验证,用cy.intercept拦截这个请求,直接返回成功响应:

cy.intercept('POST', '/api/auth/verify', {
  statusCode: 200,
  body: {
    success: true,
    userInfo: { id: 1, nickname: '测试用户' }
  }
}).as('verifyAuth');

要不要给应用加绕过机制?

不是必须,但如果你的认证逻辑嵌套复杂,Mock API的方式无法覆盖所有场景,加个测试环境专属的绕过机制会更省心:

  • 比如通过URL参数触发绕过:在应用代码里判断URL是否带有?test-bypass-auth=true,如果是就直接跳过Credential弹窗,自动登录测试账号。
  • 或者直接判断Cypress环境:
if (window.Cypress) {
  // 测试环境直接走模拟登录逻辑
  loginWithTestAccount();
} else {
  // 生产环境正常调用认证API
  navigator.credentials.get({ password: true })
    .then(cred => handleLogin(cred));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:55:17