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

使用Cypress 11时window.store为undefined的问题排查求助

问题描述

使用Cypress 11时,尝试访问window.store始终返回undefined。需要通过dispatch store数据让页面按特定配置渲染并执行测试,但因store无法访问导致后续操作无法进行。已确认window.Cypress存在,附上Cypress控制台截图:
Cypress Console

提供的index.tsx配置
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import ReactDOM from 'react-dom/client';
import App from './components/Container/App';
import { PublicClientApplication } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { msalConfig } from './authConfig';
import { store } from './app/store';
import { Provider } from 'react-redux';

const msalInstance = new PublicClientApplication(msalConfig);
const root = ReactDOM.createRoot(document.getElementById('root') || new DocumentFragment());
root.render(
    <React.StrictMode>
        <BrowserRouter>
            <MsalProvider instance={msalInstance}>
                <Provider store={store}>
                    <App />
                </Provider>
            </MsalProvider>
        </BrowserRouter>
    </React.StrictMode>
);

type CypressWindow = Window & typeof globalThis & { Cypress: any; store: any };
const testWindow = window as CypressWindow;

if (testWindow.Cypress) {
    testWindow.store = store;
}
问题排查与解决方案

核心问题:代码执行时机与构建优化冲突

你的代码中挂载store到window的逻辑放在了root.render()之后,结合React 18 createRoot的异步渲染特性,再加上部分构建工具的优化逻辑,可能导致Cypress在尝试访问window.store时,这段挂载代码还未执行,或者被构建工具误优化移除。

修复步骤

  1. 调整挂载时机
    把挂载store到window的逻辑移到root.render()之前,确保Cypress能更早捕获到store实例:
// ... 保留原有导入代码

const msalInstance = new PublicClientApplication(msalConfig);
const root = ReactDOM.createRoot(document.getElementById('root') || new DocumentFragment());

// 提前执行挂载逻辑
type CypressWindow = Window & typeof globalThis & { Cypress: any; store: any };
const testWindow = window as CypressWindow;
if (testWindow.Cypress) {
    testWindow.store = store;
}

root.render(
    <React.StrictMode>
        <BrowserRouter>
            <MsalProvider instance={msalInstance}>
                <Provider store={store}>
                    <App />
                </Provider>
            </MsalProvider>
        </BrowserRouter>
    </React.StrictMode>
);
  1. 阻止构建工具优化代码
    如果使用Vite、Webpack等工具,添加注释避免Cypress相关代码被tree-shaking移除:
// 标记代码不被构建工具移除
/* eslint-disable-next-line */
if (testWindow.Cypress) {
    testWindow.store = store;
}
  1. 在Cypress测试中添加等待逻辑
    在测试代码中增加断言,确保window.store存在后再执行dispatch操作:
cy.window().should('have.property', 'store').then((win) => {
    win.store.dispatch({ 
        type: 'YOUR_TARGET_ACTION_TYPE', 
        payload: {/* 测试数据 */} 
    });
    // 等待页面渲染完成
    cy.wait(500); // 或根据页面逻辑使用更精准的等待条件
});

额外验证点

  • 确认./app/store导出的store是正常创建的Redux实例,而非undefined
  • 检查应用中是否有其他代码意外覆盖了window.store

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:01:43