【问题标题】:How to make cypress wait for the end of a vuex action before to clean localStorage?如何让 cypress 在清理 localStorage 之前等待 vuex 操作的结束?
【发布时间】:2019-11-26 21:48:41
【问题描述】:

我使用cypress 来测试使用vuejs / vuex / graphql 制作的应用程序。感谢this great article

一个测试从组件分派vuex 操作。此操作向服务器发出多个请求。在每个请求中,将一个身份验证令牌从localStorage(如果存在)注入到headers

问题:该操作的第一个请求工作正常,但后续请求的标头中不再包含身份验证令牌并失败。据我了解,赛普拉斯在清理localStorage 之前不会等待所有请求完成。

组件

<template>
  <button @click="save">Save</button>
</template>

<script>
export default {
  methods: {
    save() {
      this.$store.dispatch('update')
    }
  }
}
</script>

商店

export const actions = {
  async update({ commit, dispatch }) {
    try {
      // the token is here
      console.log('a. token ->', localStorage.getItem('token'))

      // this works
      const res = await apiUpdate()

      // now the token is null, but why? Is it because of Cypress?
      console.log('b. token ->', localStorage.getItem('token'))

      commit('set', res)

      // this fails because the token is null in localStorage
      await apiAnotherUpdate()

    } catch (e) {
      //…
    }
  })

测试

describe("My app", () => {
  beforeEach(function() {
    cy.visit("http://localhost:8080/");

    // log the user and sets the token
    cy.login();
  });

  it("test button", function() {
    cy.get("button").click();
    cy.get("#page").should("contain", "Updated content");
  });
});

进行此测试的正确方法是什么?

谢谢


编辑

我在测试结束时使用cy.wait(2000) 发现了一个ugly 修复,但我仍然愿意接受更清洁的解决方案。

【问题讨论】:

    标签: vue.js vuex cypress


    【解决方案1】:

    在组件中创建函数async解决了它。

    methods: {
      async save() {
        await this.$store.dispatch('update')
      }
    }
    

    【讨论】:

    • 非常感谢!你拯救了我的一天。
    【解决方案2】:

    另外,您还可以使用 cypress-localstorage-commands 插件在测试之间保持 localStorage,这样您就可以只登录一次:

    在 support/commands.js 中:

    import "cypress-localstorage-commands";
    

    在你的测试中:

    before(() => {
      // Do your login stuff here
      cy.saveLocalStorage();
    });
    
    beforeEach(() => {
      cy.restoreLocalStorage();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 2016-06-16
      • 1970-01-01
      相关资源
      最近更新 更多