Search code examples
vue.jsvuexcypress

Implement login command and access vuex store


I have a login process where after sending a request to the server and getting a response, I do this:

 this.$auth.setToken(response.data.token);
 this.$store.dispatch("setLoggedUser", {
     username: this.form.username
 });

Now I'd like to emulate this behavior when testing with cypress, so i don't need to actually login each time I run a test.

So I've created a command:

Cypress.Commands.add("login", () => {
  cy
    .request({
      method: "POST",
      url: "http://localhost:8081/api/v1/login",
      body: {},
      headers: {
        Authorization: "Basic " + btoa("administrator:12345678")
      }
    })
    .then(resp => {
      window.localStorage.setItem("aq-username", "administrator");
    });

});

But I don't know how to emulate the "setLoggedUser" actions, any idea?


Solution

  • In your app code where you create the vuex store, you can conditionally expose it to Cypress:

    const store = new Vuex.Store({...})
    
    // Cypress automatically sets window.Cypress by default
    if (window.Cypress) {
      window.__store__ = store
    }
    

    then in your Cypress test code:

    cy.visit()
    // wait for the store to initialize
    cy.window().should('have.property', '__store__')
    
    cy.window().then( win => {
      win.__store__.dispatch('myaction')
    })
    

    You can add that as another custom command, but ensure you have visited your app first since that vuex store won't exist otherwise.