Search code examples
javascriptautomationmockingtestcafe

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

  • 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');
    });