当前位置: 代码迷 >> JavaScript >> testcafe RequestLogger不拦截api调用
  详细解决方案

testcafe RequestLogger不拦截api调用

热度:35   发布时间:2023-06-13 12:14:03.0

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

参考文献:

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

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

testcafe版本: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();
}

我怀疑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;  
    }
  }
}