【问题标题】:how to pass auth token fetched by axios to cy.visit in cypress test如何在赛普拉斯测试中将 axios 获取的身份验证令牌传递给 cy.visit
【发布时间】:2021-09-30 08:07:25
【问题描述】:

我正在使用 cypress 编写 e2e 测试来测试我们的 react 应用程序。在规范文件中,我在 beforeEach 中有以下代码,

describe("My Test", () => {
  beforeEach(() => {
    cy.visit(
      `/?token=${authToken}&testing=1`
    )
  })
...
}

我需要从另一个 url 获取 authToken 并且令牌每小时过期。我在单独的文件中有以下使用 axios 的代码:

import axios from "axios"

export const getAuthToken = () => {
  const data =...
  const url = `https://.../oauth2/v2.0/token`
  const config = {
    method: 'post' as const,
    url: url,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: data
  }

  return axios(config).then((response) => {
    console.log(response.data)
    return (response.data["access_token"])
  })

但我不确定如何在 beforeEach 中调用 getAuthToken?

【问题讨论】:

    标签: react-native cypress


    【解决方案1】:

    Cypress 只是 Javascript,因此您可以导入和使用该函数(如果它位于 /cypress 文件夹下的文件中,而不是 /src 的一部分)。

    import { getAuthToken } from 'path/to/file/with/getAuthToken'
    
    describe("My Test", () => {
    
      beforeEach(async () => {   make this hook async so we can await
        const authToken = await getAuthToken()
        cy.visit(
          `/?token=${authToken}&testing=1`
        )
      })
    
    }
    

    如果它是应用程序/src 的一部分,您可能无法导入它。

    另一种方法是附加对窗口的引用

    应用

    import axios from "axios"
    
    export const getAuthToken = () => {
      ...
    }
    
    if (window.Cypress) {
      window.getAuthToken = getAuthToken 
    }
    

    测试

    describe("My Test", () => {
    
      beforeEach(() => { 
        const getAuthToken = cy.state('window').getAuthToken  // get reference
        getAuthToken().then(authToken => {
          cy.visit(
            `/?token=${authToken}&testing=1`
          )
        })
      })
    
    }
    

    【讨论】:

    • 感谢您的回复。我尝试了异步方式,确实获得了身份验证令牌,但在下一个命令中出现以下错误:赛普拉斯检测到您从命令返回了一个承诺,同时还在该承诺中调用了一个或多个 cy 命令。返回 Promise 的命令是: > cy.visit() 在 Promise 中调用的 cy 命令是: > cy.customCommand() 因为 Cypress 命令已经类似于 Promise,所以你不需要包装它们或返回你的自己的承诺。
    • async/await 似乎与赛普拉斯不兼容。试试.then()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2021-12-12
    • 2021-04-13
    • 2021-10-28
    • 2020-07-30
    相关资源
    最近更新 更多