How to expose/access a data store like Redux within a cypress test?

前端 未结 2 840
孤独总比滥情好
孤独总比滥情好 2021-01-05 04:15

The Cypress docs say you can

Expose data stores (like in Redux) so you can programmatically alter the state of your application directly from your te

相关标签:
2条回答
  • 2021-01-05 05:01

    I am not sure of the exact syntax for a React app, but see this blog Testing Vue web applications with Vuex data store & REST backend.

    Vuex is the VueJs equivalent of Redux. In summary, you add a reference to the store at some point in the app startup (code snippet is modified from the blog to be a bit more generic)

    if (window.Cypress) {
      // only available during E2E tests
      window.appStore = app.store  // Substitute an appropriate expression for React Redux
    }
    

    and reference it in tests like so

    const getStore = () => cy.window().its('appStore')
    
    it('has loading, newTodo and todos properties', () => {
      getStore().its('state').should('have.keys', ['loading', 'newTodo', 'todos'])
    })
    
    0 讨论(0)
  • 2021-01-05 05:03

    Based on the answer about Vuex, I did that, which works:

    // after createStore(...)
    if (window.Cypress) {
      window.__store__ = store;
    }
    
    // in cypress tests
    cy.window().should('have.property', '__store__');
    cy.window().its('__store__')
      .then(
        store => store.dispatch({ type: 'UPDATE_CURRENT_PROFILE' })
      );
    

    Don't forget to cy.visit('anyRoute') before doing anything with the store, so that React app is started and redux store is already created when you try to access it.

    0 讨论(0)
提交回复
热议问题