如何让cypress在vuex操作结束之前等待,然后再清理localStorage?

时间:2019-11-26 21:48:41

标签: vue.js vuex cypress

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

一个测试从组件调度vuex操作。该操作向服务器发出多个请求。在每个请求中,auth令牌都从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 修复程序,但仍然可以使用更干净的解决方案。

2 个答案:

答案 0 :(得分:0)

在组件中制作函数async即可解决问题。

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

答案 1 :(得分:0)

另外,您还可以使用cypress-localstorage-commands插件在两次测试之间保留localStorage,因此您只能登录一次:

在support / commands.js中:

$userlist = Import-Csv "$home\Desktop\names.csv"

ForEach ($user in $userlist) {

    $SamID_User = $user.SamAccountName
    # $DN_User = $user.DistinguishedName
    $OU_User = $user.OU

    #A Search by SamAccountName
    $result = Get-ADUser -Filter { samaccountname -eq $SamID_User } -SearchBase $OU_User  | # DisplayName property is returned by default by Get-ADUser and hence doesn't require explicit mention
          Select-Object Name,DisplayName

    $result | Export-CSV "$home\Desktop\new_names.csv" -NoTypeInformation -Append # Added -Append switch; works on PS v3.0 and later; with PS v2.0 -Append switch is not available with Export-Csv; With PS v2.0 you can use Out-File instead

    #B Search by DistinguishedName
    <#
    $result = Get-ADUser -Filter { DistinguishedName -eq $DN_User } -SearchBase $OU_User | 
          Select-Object Name,DisplayName
    $result | Export-CSV "$home\Desktop\new_names.csv" -NoTypeInformation -Append
    #>

}

在您的测试中:

import "cypress-localstorage-commands";