首页 > 解决方案 > testcafe RequestLogger 不拦截 api 调用

问题描述

出于某种原因,我无法让 testcafe 的 RequestLogger 记录我正在进行的任何 API 调用。我已经阅读了几乎所有关于 RequestLogger 的文章和问题,并且所有内容都指向与以下代码相同的工作。不知道我做错了什么,任何帮助都会很棒。

参考:

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

无法使用 Testcafe 拦截来自页面的传出 AJAX 请求

如何在 Testcafe 中记录 Google Analytics 调用?

我在本地运行并访问了一个也在本地运行的 API,前端在端口 3000 上,后端在端口 8080 上,API 位于:8080/api/admin。我可以看到记录器被注入到测试中,但没有更新它,它只是一个带有初始道具的平淡对象,并且会在 t.expect 语句之后出错。

我想知道 beforeEach 是否破坏了某些东西,但我需要它来触发任何 API 调用,因为需要对用户进行身份验证。我可以看到调试时调用的 API 请求,我试图拦截,但没有运气

测试咖啡馆版本:1.0.0 || 0.23.3

测试代码

// 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();
}

标签: javascripttypescriptautomated-testse2e-testingtestcafe

解决方案


我怀疑 TestCafe 比调用 api 的代码运行得更快。

在使用记录器对象之前,您应该等待它至少收到一个调用。

要检查记录器是否已接到电话,我建议这样做:

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

推荐阅读