we are trying to implement functional testing using testcafe. Because of our complex backend systems, we will not be able to hit the actual API in some scenario (like OTP, backend account lock) without manual intervention. To circumvent this we have decided to run a stub server for certain endpoints.
In order to achieve this, we wanted to modify the URL of API in our test code. We thought of using a custom request hook to change the URL. Although the URL changes in the object, the browser hits the actual 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();
Currently you can't change the destination URL of a request using the requestEvent.requestOptions.url property, I've created an issue about this: DevExpress/testcafe#2635. You should use the hostname, port and path properties:
requestEvent.requestOptions.hostname = 'localhost';
requestEvent.requestOptions.port = 4200;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With