Javascript Testcafe如何读取json响应并选择第一项并将其传递给选择器
读取JSON响应 1) 当我访问这个URL“http:example.com/fruits”时,它会碰到一个端点“http:example.com/v1/collections/fruits”,我在浏览器网络响应中看到JSON:Javascript Testcafe如何读取json响应并选择第一项并将其传递给选择器,javascript,json,automated-tests,e2e-testing,testcafe,Javascript,Json,Automated Tests,E2e Testing,Testcafe,读取JSON响应 1) 当我访问这个URL“http:example.com/fruits”时,它会碰到一个端点“http:example.com/v1/collections/fruits”,我在浏览器网络响应中看到JSON: { "total":3, "page":1, "pageSize":24, "rows":[ { "id":19, "title":"Apple" }, {
{
"total":3,
"page":1,
"pageSize":24,
"rows":[
{
"id":19,
"title":"Apple"
},
{
"id":21,
"title":"Grape",
},
{
"id":6,
"title":"Orange",
},
]
}
2) 我想拿起第一个标题-Apple并将其传递给选择器,然后在应用程序中单击它,您可以创建“获取”方法,如:
fetch('http:example.com/v1/collections/fruits', {
method: 'GET'
})
.then(response => response.json())
.then(data => {
console.log(data.rows[0]['title']) // should return 'Apple'
})
.catch(error => console.error(error))
然后,您可以将其传递给选择器。您也可以使用来获取此信息
这可能存在于帮助文件中
import { RequestHook } from 'testcafe';
export default class MyRequestHook extends RequestHook {
constructor (requestFilterRules, responseEventConfigureOpts,ObjToReturn) {
super(requestFilterRules, responseEventConfigureOpts);
this.ObjToReturn = ObjToReturn;
}
onRequest (event) {
if(event.isAjax) {
console.log(event.requestOptions.url);
}
}
onResponse (event) {
this.ObjToReturn = JSON.parse(event.body.toString());
}
}
然后,这将出现在您的主测试文件中:
import { Selector } from 'testcafe';
import MyRquestHook from './MyHTTPRequestFile';
let getReponse = {};
const hookConfigOptions = {
logResponseBody: true,
stringifyResponseBody: true,
includeHeaders: true,
includeBody: true
}
let getFruits = new MyRequestHook({url:'http://example.com/fruits', method: 'get'},hookConfigOptions,getResponse);
fixture `Name Of test`
.requestHooks(getFruits)
test('Do something with response', async t => {
//do something with the response object
console.log("Response Data: " + getFruits.rows[0]['title']
}
“将其传递给选择器并单击它”的确切含义是什么?@Brainfeeder用标题识别正确的选择器,然后指示testcafe单击所述选择器。啊,是的,testcafe文档中的答案和示例应适用于OP then。。?