如何使用cypress模拟vuex存储操作

Tom*_*mer 2 vue.js vuex cypress

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

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

现在,我想在使用赛普拉斯进行测试时模拟这种行为,因此我不需要每次运行测试时都实际登录。

所以我创建了一个命令:

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

});
Run Code Online (Sandbox Code Playgroud)

但是我不知道如何模仿“ setLoggedUser”操作,有什么想法吗?

bku*_*era 5

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

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

// Cypress automatically sets window.Cypress by default
if (window.Cypress) {
  window.__store__ = store
}
Run Code Online (Sandbox Code Playgroud)

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

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

cy.window().then( win => {
  win.__store__.dispatch('myaction')
})
Run Code Online (Sandbox Code Playgroud)

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