TestCafe RequestLogger - How to wait for all responses to return before doing an assertion on each request object

Viewed 1258

See the attached screenshot. I have a RequestLogger that captures all the requests to /api/dynamic_reporting/filters/*/find endpoint.

The issue is that when I do an assertion await t.expect(dynamicReportingFindRequest.requests[1].response.statusCode).eql(200,'Did not get 200 OK response'), I get an error Cannot read property 'statusCode' of undefined because the xhr is still pending for requests[1], requests[2]... and hasn't completed yet.

How do I wait for all responses to return before doing an assertion on the requests?

enter image description here

1 Answers

I would suggest the following solution based on the idea from the testcafe RequestLogger not intercepting api calls question:

Here is simple node.js server:

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);

Click on the button sends 3 requests.

And the test code is the following:

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);
});
Related