How to emulate vuex store action with cypress

那年仲夏 提交于 2019-12-12 10:05:45

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/51122303/how-to-emulate-vuex-store-action-with-cypress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!