puppeteer .respond()

Mocking api calls responses can be really helpful and add a great deal to an automation framework. Frameworks built using puppeteer can utilize the out of the box methods to achieve api mocking.
The basic concept is initiating the API calls, intercepting all the calls and identifying the one that has to be mocked , mocking the response for this call and whilst continuing with the other calls.

For instance: If we were to mock the response for the login api call. Then all we need to do is :
1) Store the mock response in a json file
2) Intercept the call
3) Let other calls continue
4) Respond to login api call with the mock json response

await page.setRequestInterception(true);
page.on('request', request => {
    if (request.url() === loginAPI) {
        request.respond(mock)
        }
    request.continue();
});

where mock is:
mock(url, body, status = 200, method = 'GET', headers = []) {
        if (body != null) {
            this.mocks = [
                ...this.mocks,
                {
                    url,
                    body: _.isString(body) ? body : JSON.stringify(body),
                    status,
                    method,
                    headers,
                },
            ];
        }
    }

Now this mock method is called to add the requests to this.mocks array, e.g
mock('/api/login/account',path to your json mock response)


Comments

Popular Posts