首页 > 解决方案 > 实现登录命令并访问 vuex 存储

问题描述

我有一个登录过程,在向服务器发送请求并得到响应后,我这样做:

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

现在我想在使用 cypress 进行测试时模拟这种行为,所以每次运行测试时我都不需要实际登录。

所以我创建了一个命令:

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");
    });

});

但我不知道如何模拟“setLoggedUser”动作,知道吗?

标签: vue.jsvuexcypress

解决方案


在您创建 的应用程序代码中vuex store,您可以有条件地将其公开给赛普拉斯:

const store = new Vuex.Store({...})

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

然后在您的赛普拉斯测试代码中:

cy.visit()
// wait for the store to initialize
cy.window().should('have.property', '__store__')

cy.window().then( win => {
  win.__store__.dispatch('myaction')
})

您可以将其添加为另一个自定义命令,但请确保您首先访问了您的应用程序,否则该 vuex 商店将不存在。


推荐阅读