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

使用Cypress无法获取Vuex状态,按博客操作仍遇异常

Troubleshooting Accessing Vuex Store via window.app

Hey there! Let's break down what's going on with your Vuex store access issue and work through fixes for both the browser console and Cypress.

1. Why app.$store Isn't Available (But app.store Is)

The blog's setup likely uses Vuex's official mounting method, which automatically injects the store as $store—your code might be skipping this step:

  • For Vue 2: The standard flow is Vue.use(Vuex) followed by passing the store to new Vue({ store })—this adds $store to the app instance automatically.
  • For Vue 3: You need to call app.use(store) right after creating your app with createApp(). This also attaches the store as $store to the app.

If you manually assigned the store to app.store instead of using use(), that's why $store is missing. Try switching to the official Vuex mounting method first—it'll align with the blog's instructions.

2. Why app.store Has No state Property

Vuex stores do have a state property, but it might be wrapped or hidden depending on your Vuex version:

  • For Vuex 4 (Vue 3): The raw reactive state lives under store._state.data (the _state object is a Vue reactivity wrapper).
  • If you're using a custom wrapper around the Vuex store, the state might be intentionally not exposed directly at the top level.

First, open your browser console and run:

console.log(app.store)

Inspect the output to find where the state is nested—it could be under _state.data, state.value, or another path. Once you locate it, you can access it directly (e.g., app.store._state.data).

3. Fixing the Cypress Access Issue

When using cy.window().its('app.store'), Cypress might be trying to access the store before it's fully initialized. Here's how to fix that:

  • Wait for the app and store to exist before accessing them:
    cy.window()
      .should('have.property', 'app')
      .should('have.property', 'store')
      .then(win => {
        // Use the state path you found earlier
        const storeState = win.app.store._state.data;
        // Example assertion
        expect(storeState.user.isLoggedIn).to.be.true;
      });
    
  • Alternatively, chain its() calls if you know the exact state path:
    cy.window().its('app.store._state.data.user.isLoggedIn').should('be.true');
    

Quick Recap

  1. Use Vuex's official mounting method (app.use(store) for Vue 3, or Vue 2's standard setup) to get app.$store working like the blog describes.
  2. Inspect app.store in the browser console to find the actual nested state property.
  3. In Cypress, add assertions to wait for the app and store to finish initializing before accessing their properties.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:38:01