如何在Protractor中通过ChromeDriver获取含请求头与请求体的HTTP请求日志
Absolutely! You can capture detailed HTTP request logs (including headers and bodies) using ChromeDriver's performance logging feature. Here's a step-by-step guide to get this working:
1. Update Your Protractor Configuration
First, modify your protractor.conf.js to enable performance logging and target network-specific events. Add these settings under the capabilities object:
exports.config = { // ... other existing config options capabilities: { browserName: 'chrome', loggingPrefs: { performance: 'ALL' // Capture all performance-related log entries }, chromeOptions: { perfLoggingPrefs: { enableNetwork: true, // Focus on network events enablePage: false, // Disable page load logs to reduce noise enableTimeline: false // Disable timeline logs unless needed } } }, // ... rest of your config };
2. Create a Helper Function to Extract Request Details
Add a reusable function to your test suite that parses raw performance logs and extracts the data you care about. This function will map request headers and bodies together by their unique request ID:
async function getHttpRequestDetails() { // Fetch raw performance logs from ChromeDriver const rawLogs = await browser.manage().logs().get('performance'); // Parse each log entry (they're stored as JSON strings) const parsedLogs = rawLogs.map(entry => JSON.parse(entry.message).message); // Extract request header data const requestHeaders = parsedLogs .filter(event => event.method === 'Network.requestWillBeSent') .map(event => ({ requestId: event.params.requestId, url: event.params.request.url, method: event.params.request.method, headers: event.params.request.headers })); // Extract request body data (only for POST/PUT requests) const requestBodies = parsedLogs .filter(event => event.method === 'Network.requestBodySent') .map(event => ({ requestId: event.params.requestId, body: event.params.request.postData })); // Merge headers and bodies into a single array of request details return requestHeaders.map(headerEntry => ({ ...headerEntry, body: requestBodies.find(bodyEntry => bodyEntry.requestId === headerEntry.requestId)?.body || null })); }
3. Use the Helper in Your Test Scenarios
Call this function after triggering the HTTP request action to retrieve and inspect the logs. Here's an example test case:
describe('Angular App E2E Tests', () => { it('should capture API request headers and body', async () => { // Navigate to the page with the request trigger await browser.get('/submit-form'); // Perform an action that sends an HTTP request await element(by.css('#submit-button')).click(); // Wait for the request to complete (adjust timeout as needed) await browser.waitForAngular(); // Or use explicit waits for better reliability // Get and log the request details const requestLogs = await getHttpRequestDetails(); console.log('Captured HTTP Requests:', JSON.stringify(requestLogs, null, 2)); // Assert against specific request properties const apiRequest = requestLogs.find(log => log.url.includes('/api/submit')); expect(apiRequest.method).toBe('POST'); expect(apiRequest.headers['Content-Type']).toBe('application/json'); expect(apiRequest.body).toContain('user-input-value'); }); });
Key Tips for Success
- Filter Logs: Add URL-specific filters to the helper function to ignore irrelevant requests (like static assets) and focus on your API calls.
- Timing: Use explicit waits (instead of hardcoded
sleep()calls) to ensure the request completes before retrieving logs. - Compatibility: Make sure your ChromeDriver version matches your installed Chrome browser to avoid logging inconsistencies.
- Body Availability: The
Network.requestBodySentevent only exists for requests with a payload (POST/PUT). GET requests won't have this entry.
内容的提问来源于stack exchange,提问作者cartman

