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

使用Cypress测试Redux状态键值对报错,如何修复?

问题

我已按如下方式配置Redux Store:

ReactDOM.render(
  <CookiesProvider>
    <Provider store={store}>
      <App />
    </Provider>
  </CookiesProvider>,
  document.getElementById('root'),
)

if (window.Cypress) {
  window.Cypress.store = store
}

我想要检查Redux中store.auth.user.account.person.email这个字符串类型的邮箱值是否存在,尝试编写如下测试代码:

it.only('checks if email is being shown', () => {
  cy.get('.email-button')
  .should(() => {
      Cypress.store.getState().then(state => {
        console.log("state", state);
      expect(state.auth.user.account.person.email).to.equal('asfasdf')
    })
  })
})

但测试失败,报错信息如下:

Timed out retrying after 4000ms: Cypress.store.getState(...).then is not a function

  40 |     cy.get('.contact-button.email')
  41 |     .should(() => {
> 42 |         Cypress.store.getState().then(state => {
     |                                  ^
  43 |           console.log("state", state);
  44 |         expect(state.token).to.equal('asfasdf')
  45 |       })

请问我哪里操作有误?该如何修复这个问题?


错误原因与修复方案

错误点解析

  • Redux的getState()是同步方法,直接返回当前状态,不是Promise,所以不能调用.then(),这是报错的核心原因。
  • 你把expect断言嵌套在不存在的.then()回调里,导致逻辑无法正常执行,进而触发超时重试。

修复后的测试代码

it.only('checks if email is being shown', () => {
  cy.get('.email-button')
    .should(() => {
      // 同步获取Redux状态
      const state = Cypress.store.getState();
      console.log("state", state);
      // 直接断言邮箱值
      expect(state.auth.user.account.person.email).to.equal('asfasdf');
    });
});

额外优化建议

如果邮箱值是通过异步请求(比如登录接口)加载到Redux的,建议先等待状态初始化完成,避免断言过早执行:

it.only('checks if email is being shown', () => {
  // 等待auth用户状态加载完成
  cy.wrap(null).should(() => {
    const state = Cypress.store.getState();
    expect(state.auth.user).to.exist;
  });

  cy.get('.email-button')
    .should(() => {
      const state = Cypress.store.getState();
      expect(state.auth.user.account.person.email).to.equal('asfasdf');
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 13:30:51