Testcafe - 如何使用 JSON 响应数据作为变量

Testcafe - How to use JSON response data as a variable

我想添加一个 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})

我还有一个来自赛普拉斯的工作代码

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

的输入

您可以在 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));

参考文献:

这是一种解决方法,但可以使用节点提取

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

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