You need to enable JavaScript to run this app. 使用Cypress Session时测试失败,请求技术排查
优惠活动
大模型
产品
解决方案
定价
更多

使用Cypress Session时测试失败,请求技术排查

问题:Cypress 后台认证会话导致应用抛出 TypeError 错误

我编写了如下代码实现后台认证:

export function backofficeAuthenticate(username, password) {
    cy.session(['Login'], () => {
        cy.request({
            log: false,
            method: 'POST',
            url: getBackUrl('/login.htm'),
            qs: {
                redir: getBackUrl('/back'),
            },
            followRedirect: false,
            body: {
                'Login_login-email': username,
                'Login_login-password': password,
                'action[Login_login:login]': 'login',
            },
        });
      });
}

并通过以下函数调用登录:

export function loginWithAdmin() {
    backofficeAuthenticate(Cypress.env('WEB_LOGIN_USERNAME'), Cypress.env('WEB_LOGIN_PASSWORD'));
}

我的测试代码如下:

import { loginWithAdmin, httpAuthentication } from '../../cypress/support/bestreviews.js';

describe('Dashboard types quick smoke', () => {

    const endpoints = [
        '/dashboard',
        '/dashboard/articles',
        '/dashboard/archive',
        '/dashboard/syndicated',
        '/dashboard/tribunearticles',
        '/dashboard/giftguides',
        '/dashboard/blogposts',
    ];

    endpoints.forEach((endpoint) => {
            it(endpoint, () => {
                cy.visitBackOffice(endpoint);
                httpAuthentication();
                loginWithAdmin();
                cy.checkErrorFree();
                cy.get('.dashboard-entries').should('exist');
                cy.get('[data-content="topic-info"]').should('exist');
            });
        });
    });

执行代码后,始终遇到如下错误:

(uncaught exception) TypeError: Cannot read properties of null (reading 'style')
TypeError The following error originated from your application code, not from Cypress.

Cannot read properties of null (reading 'style')

When Cypress detects uncaught errors originating from your application it will automatically fail the current test.

This behavior is configurable, and you can choose to turn this off by listening to the uncaught:exception event.

我怀疑问题出在Cypress Session上,但不确定如何排查,请问我遗漏了什么?


排查与解决方法

1. 会话创建时机错误

当前流程是先访问页面再执行认证,会导致未认证状态下页面先加载,应用代码尝试操作不存在的DOM元素(比如读取某个元素的style),从而抛出null错误。

正确顺序应为先完成会话认证,再访问受保护页面:

it(endpoint, () => {
    loginWithAdmin(); // 优先建立认证会话
    httpAuthentication(); // 若需HTTP基础认证,调整到访问前执行
    cy.visitBackOffice(endpoint); // 最后访问页面
    cy.checkErrorFree();
    cy.get('.dashboard-entries').should('exist');
    cy.get('[data-content="topic-info"]').should('exist');
});

2. Cypress Session 缺少验证与配置

cy.session 需要确保认证请求成功,且会话凭证被正确存储。可以添加验证步骤:

export function backofficeAuthenticate(username, password) {
    cy.session(['Login'], () => {
        cy.request({
            log: false,
            method: 'POST',
            url: getBackUrl('/login.htm'),
            qs: {
                redir: getBackUrl('/back'),
            },
            followRedirect: false,
            body: {
                'Login_login-email': username,
                'Login_login-password': password,
                'action[Login_login:login]': 'login',
            },
        })
        .its('status').should('eq', 302); // 验证登录请求返回重定向,确认认证成功
        cy.getCookie('your_auth_cookie_name').should('exist'); // 验证认证Cookie存在
    }, {
        cacheAcrossSpecs: true, // 如需跨测试文件复用会话,开启此配置
    });
}

3. 临时捕获未认证场景的JS错误

如果必须先访问页面,可临时忽略特定异常,避免测试中断,同时定位问题元素:

Cypress.on('uncaught:exception', (err, runnable) => {
    if (err.message.includes("Cannot read properties of null (reading 'style')")) {
        return false; // 忽略该错误,继续测试
    }
    // 其他错误正常抛出
});

注意:这是临时方案,核心仍需确保访问页面时用户已完成认证。

4. HTTP认证与会话的顺序冲突

如果httpAuthentication()是处理HTTP基础认证,需确保它在cy.visit或cy.request之前执行,否则请求会因未通过HTTP认证失败,导致会话无效。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 11:39:47