【问题标题】:Testcafe - How to use JSON response data as a variableTestcafe - 如何使用 JSON 响应数据作为变量
【发布时间】:2019-10-22 10:48:50
【问题描述】:

我想添加一个 testcafe 步骤,在该步骤中我调用 API GET 并使用 JSON 响应正文中的某些内容作为输入到字段中的测试。

如何在 TestCafe 中实现此功能?

我试图使用 https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/logging-http-requests.html 中的 RequestLogger 但这不起作用,它没有发出任何请求。

这是在控制台中使用时有效的提取:

var SMScodeField = document.querySelector(`input#code`)

fetch(
//call the API to get the SMS code
  `https://app.website.com/api/test-helper/getLastSMS`)
  .then(response => response.json())
//use the code value as input into pre-defined field SMScodeField
  .then(data => {SMScodeField.value = data.sms[0].code})

我还有一个来自 Cypress 的工作代码

cy.request(`https://app.website.com/api/test-helper/getLastSMS`)
  .then((response) => {
     let body = JSON.parse(response.body)
     cy.get(`input#code`).type(body._embedded.sms[0].code)
   })

如何在 TestCafe 中实现此行为?我只需要在调用 https://app.website.com/api/test-helper/getLastSMS 时从 JSON 响应中获取 code 并将其用作字段 SMScodeField 的输入

【问题讨论】:

    标签: json testing automated-tests httpresponse testcafe


    【解决方案1】:

    您可以在 TestCafe 测试中使用标准的 nodejs 代码。只需使用 axios 或 node-fetch 获取数据并在稍后的测试中使用它们。

    npm i -D axios @types/axios
    
    import axios from 'axios';
    
    axios.get('https://app.website.com/api/test-helper/getLastSMS')
       .then(response => console.log(response));
    

    参考资料:

    【讨论】:

      【解决方案2】:

      这是一种解决方法,但可以使用 node-fetch

      https://www.npmjs.com/package/node-fetch

      还没有尝试过,但我真的很想使用 TestCafe 原生的东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        • 2010-11-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多