使用Cypress无法获取Vuex状态,按博客操作仍遇异常
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 tonew Vue({ store })—this adds$storeto the app instance automatically. - For Vue 3: You need to call
app.use(store)right after creating your app withcreateApp(). This also attaches the store as$storeto 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_stateobject is a Vue reactivity wrapper). - If you're using a custom wrapper around the Vuex store, the
statemight 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
appandstoreto 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
- Use Vuex's official mounting method (
app.use(store)for Vue 3, or Vue 2's standard setup) to getapp.$storeworking like the blog describes. - Inspect
app.storein the browser console to find the actual nested state property. - In Cypress, add assertions to wait for the app and store to finish initializing before accessing their properties.
内容的提问来源于stack exchange,提问作者musicformellons

