Support redirects in NewtorkManager

This patch adds support to redirects so that they will be reported
as a separate requests.

References #26.
This commit is contained in:
Andrey Lushnikov 2017-06-29 18:54:01 -07:00
parent 7f74daf62c
commit 9c138e9dba
3 changed files with 36 additions and 0 deletions

View File

@ -92,6 +92,13 @@ class NetworkManager extends EventEmitter {
* @param {!Object} event
*/
_onRequestWillBeSent(event) {
if (event.redirectResponse) {
let request = this._idToRequest.get(event.requestId);
let response = new Response(request, event.redirectResponse);
request._response = response;
this.emit(NetworkManager.Events.Response, response);
this.emit(NetworkManager.Events.RequestFinished, request);
}
let request = new Request(event.request);
this._idToRequest.set(event.requestId, request);
this.emit(NetworkManager.Events.Request, request);

View File

@ -54,6 +54,17 @@ class StaticServer {
this._routes.set(path, handler);
}
/**
* @param {string} fromPath
* @param {string} toPath
*/
setRedirect(from, to) {
this.setRoute(from, (req, res) => {
res.writeHead(302, { location: to });
res.end();
});
}
/**
* @param {string} path
* @return {!Promise<!IncomingMessage>}

View File

@ -547,6 +547,24 @@ describe('Puppeteer', function() {
await page.navigate(EMPTY_PAGE);
expect(events).toEqual(['request', 'response', 'requestfinished']);
}));
it('should support redirects', SX(async function() {
let events = [];
page.on('request', request => events.push(`${request.method} ${request.url}`));
page.on('response', response => events.push(`${response.status} ${response.url}`));
page.on('requestfinished', request => events.push(`DONE ${request.url}`));
page.on('requestfailed', request => events.push(`FAIL ${request.url}`));
staticServer.setRedirect('/foo.html', '/empty.html');
const FOO_URL = STATIC_PREFIX + '/foo.html';
await page.navigate(FOO_URL);
expect(events).toEqual([
`GET ${FOO_URL}`,
`302 ${FOO_URL}`,
`DONE ${FOO_URL}`,
`GET ${EMPTY_PAGE}`,
`200 ${EMPTY_PAGE}`,
`DONE ${EMPTY_PAGE}`
]);
}));
});
});