'How do i modify browser network call request body using TestCafe

I want to modify the API request body by interrupting the network calls using Testcafe. I am aware I can modify the response body but I want to modify the request body instead, using testCafe's RequestMock().

Load the web app > Find the API using filter > Modify the request body > Pass the actual response to the web app



Solution 1:[1]

You can implement a Custom Request Hook to modify the request body.

For example:

import { RequestHook } from "testcafe";

export class MyRequestHook extends RequestHook {
    onRequest (event) {
        if (event.requestOptions?.body)
            event.requestOptions.body = Buffer.from(event.requestOptions.body, "utf8");
    }
    onResponse (event) {}
}

const customHook = new MyRequestHook(/api/); 

fixture`Modify Request Body`
    .page`http://localhost:3001`
    .requestHooks(customHook);

test('Test', async t => {
    await t.click('button');
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Ostashev