请参阅随附的屏幕截图。我有一个 RequestLogger,它捕获对 /api/dynamic_reporting/filters/*/find
端点的所有请求。
问题是,当我执行断言时 await t.expect(dynamicReportingFindRequest.requests[1].response.statusCode).eql(200,'Did not get 200 OK response')
,我收到错误无法读取未定义的属性“statusCode”
,因为 xhr 仍在等待 requests[1]、requests[2]...
并且尚未完成还没有。
在对请求进行断言之前,如何等待所有响应返回?
最佳答案
我会根据 testcafe RequestLogger not intercepting api calls 的想法建议以下解决方案问题:
这是简单的 Node.js 服务器:
var http = require('http');
http.createServer(function (req, res) {
if (req.url.indexOf('test') > -1) {
setTimeout(() => {
res.writeHead(200, {'Content-Type': 'application/json'});
res.write('rest');
res.end();
}, 10000);
}
else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(`<button onclick="fetch('http://localhost:8082/test'); setTimeout(() => { fetch('http://localhost:8082/test'); }, 100);setTimeout(() => { fetch('http://localhost:8082/test'); }, 200)">button</button>`);
res.end();
}
}).listen(8082);
点击按钮会发送 3 个请求。
测试代码如下:
import { RequestLogger } from 'testcafe';
const logger = RequestLogger(/test/);
fixture `Getting Started`
.page `http://localhost:8082`;
test.requestHooks(logger)('My first test', async t => {
await t.click('button');
while (logger.requests.find(r => !r.response || r.response.statusCode !== 200))
await t.wait(1000);
console.log(logger.requests.length);
console.log(logger.requests.filter(r => r.response.statusCode === 200).length);
});
关于testing - TestCafe RequestLogger - 在对每个请求对象进行断言之前如何等待所有响应返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62798820/