代码之家  ›  专栏  ›  技术社区  ›  Tomer

如何用cypress模拟vuex存储操作

  •  2
  • Tomer  · 技术社区  · 7 年前

    我有一个登录过程,在向服务器发送请求并获得响应后,我执行以下操作:

     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”的动作,知道吗?

    1 回复  |  直到 7 年前
        1
  •  5
  •   kuceb    7 年前

    在你的应用程序代码中创建 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商店不会存在。