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