【问题标题】:Change request URL in requesthook更改 requesthook 中的请求 URL
【发布时间】:2018-07-16 04:59:50
【问题描述】:

我们正在尝试使用 testcafe 实现功能测试。由于我们复杂的后端系统,在某些情况下(如 OTP、后端帐户锁定),如果没有人工干预,我们将无法访问实际的 API。为了避免这种情况,我们决定为某些端点运行存根服务器。

为了实现这一点,我们想在我们的测试代码中修改 API 的 URL。我们考虑使用自定义请求挂钩来更改 URL。尽管对象中的 URL 发生了变化,但浏览器会点击实际的 API URL。

import { RequestHook } from "testcafe";

class CustomRequestHook extends RequestHook {

   constructor() {
       super();
   }

   onRequest(requestEvent: any) {
   try {

        if (requestEvent.isAjax && requestEvent.requestOptions.isXhr && requestEvent.requestOptions.path.indexOf('.') === -1) {
    console.log(requestEvent.requestOptions.path);
    console.log("Before:", requestEvent.requestOptions.url);
    requestEvent.requestOptions.url = 'http://localhost:4200' + requestEvent.requestOptions.path;
    // requestEvent.requestOptions.host = 'localhost:4200';
    // requestEvent.requestOptions.hostname = 'localhost:4200';
    console.log("After:", requestEvent.requestOptions.url);
    requestEvent.requestOptions.headers['custom-header'] = 'value';
    // requestEvent.requestOptions.headers['host'] = 'localhost:4200';
  }
} catch (error) {
  console.log("Error:", error);

  // requestEvent.requestOptions.url = "www.google.com";
}
}
 onResponse(responseEvent: any) {
  console.log("response", responseEvent)
 }
}

export const CustomRequestHookInstance = new CustomRequestHook();

【问题讨论】:

  • Hook 附加到测试方法。

标签: testing automated-tests e2e-testing web-testing testcafe


【解决方案1】:

目前您无法使用 requestEvent.requestOptions.url 属性更改请求的目标 URL,我已经创建了一个关于此的问题:DevExpress/testcafe#2635。您应该使用hostname、port 和path 属性:

requestEvent.requestOptions.hostname = 'localhost';
requestEvent.requestOptions.port     = 4200; 

【讨论】:

  • 嗨@Andrey Belym,感谢您的回复。我尝试按照建议更改主机名、端口和路径,但测试仍在使用实际 API 而不是修改后的 API。
    requestEvent.requestOptions.path = 'http://localhost:4200'+requestEvent.requestOptions.path; // requestEvent.requestOptions.url = 'http://localhost:4200'+requestEvent.requestOptions.path; requestEvent.requestOptions.hostname = 'localhost'; requestEvent.requestOptions.port = 4200;
  • 您的代码中有一个复杂的条件:requestEvent.isAjax && requestEvent.requestOptions.isXhr && requestEvent.requestOptions.path.indexOf('.') === -1,我会记录它的每个部分。另外,我在requestEvent.requestOptions 属性列表中找不到isXhr 属性:devexpress.github.io/testcafe/documentation/test-api/…
  • 删除了除了检查api 的路径之外的所有条件(可以使用过滤器完成,但在它工作后会重构)。仍然没有运气。尝试了主机名、主机、协议、url 和路径的各种组合。 console.log(requestEvent.requestOptions.path); if (requestEvent.requestOptions.path.indexOf("/api") > -1) { console.log("comes inside"); .... other logic...... }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 2021-05-02
  • 1970-01-01
相关资源
最近更新 更多