Search code examples
javascripttypescriptautomated-testse2e-testingtestcafe

testcafe RequestLogger not intercepting api calls


For some reason, I cannot get testcafe's RequestLogger to log any of the API calls that I am making. I've read nearly all of the articles and questions on the RequestLogger and everything is pointing to what appears to be the same as the below code as working. Not sure what I'm doing wrong, any help would be great.

References:

https://devexpress.github.io/testcafe/documentation/test-api/intercepting-http-requests/logging-http-requests.html

Cannot intercept outgoing AJAX request from page using Testcafe

How to log Google Analytics calls in Testcafe?

I am running locally and hitting an API that is running locally as well, front-end on port 3000 and backend on port 8080, API is at: 8080/api/admin. I can see the logger as injected into the test but nothing updates it, its just a bland object with initial props and will error out after the t.expect statement.

I wonder if the beforeEach is breaking something but I need it in order to fire any API calls because the user needs to be authenticated. I can see the API request being called when debugging, that I am trying to intercept, but no luck

testcafe version: 1.0.0 || 0.23.3

Test code

// have tried several urls, from exact to generic to ports.
const logger = RequestLogger("/api/", {
  logRequestHeaders: true,
  logRequestBody: true
});

const url = 'localhost:3000/reports';

fixture `Report`
  .page(url)
  .requestHooks(logger)
  .beforeEach(async (t: TestController) => {
    await loginAndNavToReports({ t });
  });

test("Reports", async (t: TestController) => {
  // this fires an api call through the /api/ path
  await t.click(".test-reportLaborSummary");
  // have tried several comparisons here, all fail or expect falsey to be truthy errors
  await t.expect(logger.count(() => true)).ok();
}

Solution

  • I suspect that TestCafe runs faster than the code that calls the api.

    Before using the logger object you should wait that it has received at least one call.

    To check if the logger has received a call, I suggest to do it this way:

    await wait_for_first_request();
    const receivedCalls = logger.requests.length;
    if (receivedCalls === 0) {
      throw new Error('api has not been called')
    }
    
    
    async function wait_for_first_request() {
      for (let i = 0; i < 50; i++) {
        await t.wait(100);
        if (logger.requests.length > 0 ) {
          return;  
        }
      }
    }