Fix Angular E2E File Downloads in Headless Chrome
In this article
Fixing Angular end-to-end (E2E) file downloads in headless Chrome ensures that automated tests reliably simulate real user behavior when files are downloaded during browser interactions. Without proper configuration, headless Chrome blocks or misroutes downloads, leading to flaky tests or false failures. This guide walks through configuring Protractor or WebDriver-based E2E tests to allow and verify file downloads programmatically in headless mode, using Chrome's DevTools Protocol and custom preferences.
What You'll Need
- Angular application with Protractor or WebDriver-based E2E tests
- ChromeDriver version compatible with your Chrome browser
- Node.js and npm installed
- Basic understanding of Protractor or WebDriver configuration
- A test that triggers a file download (e.g., PDF, CSV export)
Step-by-Step
- Locate your Protractor or WebDriver configuration file (usually
protractor.conf.jsorwdio.conf.jsfor WebdriverIO). - Define a dedicated download directory for test artifacts. Create a folder like
e2e/downloadsin your project root to isolate downloaded files from source code. - Modify Chrome options in the capabilities section to include download preferences. Add the following to the
chromeOptionsobject:
Replace the path with an absolute path using"prefs": { "download.default_directory": "/path/to/your/project/e2e/downloads", "download.prompt_for_download": false, "download.directory_upgrade": true, "safebrowsing.enabled": true }path.resolve(__dirname, 'downloads')to ensure portability. - Enable headless mode with additional flags for stability. Include:
The"--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--disable-extensions", "--disable-plugins-discovery", "--disable-background-networking", "--disable-sync"--headless=newflag ensures compatibility with modern Chrome versions. - If using Protractor, ensure
directConnect: trueor that ChromeDriver is properly started. For WebdriverIO, confirm the browser service is correctly initialized. - Within your test, trigger the file download action (e.g., click a button that initiates a GET request to a file endpoint).
- Pause execution briefly to allow the download to complete. Use
browser.sleep(3000)or a more reliable wait condition based on file existence. - Verify the file was downloaded by checking the file system. Use Node.js
fsmodule to confirm the file exists:const fs = require('fs'); const downloadedFile = '/path/to/your/project/e2e/downloads/export.csv'; expect(fs.existsSync(downloadedFile)).toBe(true); - Optionally, validate file size or content. For a CSV, read the first few lines to confirm headers match expectations.
- Clean up after the test. Delete the downloaded file using
fs.unlinkSync(downloadedFile)to prevent test pollution.
Common Mistakes
- Using relative paths in
download.default_directory— Chrome may resolve them incorrectly. Always use absolute paths. - Forgetting to disable
prompt_for_download— this causes Chrome to show a save dialog even in headless mode, blocking automation. - Not waiting long enough after triggering the download — network delays or large files may require longer waits than expected.
- Running tests in parallel without isolated download directories — multiple tests writing to the same folder cause race conditions.
- Assuming downloads work the same in headed and headless modes — headless Chrome may block certain download triggers unless explicitly allowed.
Tips
- Use a timestamped or UUID-based subdirectory for each test run to prevent file collisions in parallel execution.
- Log the download directory path during test setup to aid debugging.
- Instead of fixed sleeps, implement a retry loop that checks for file presence every 500ms up to 10 seconds.
- Mock backend responses when possible to return small, predictable files for faster, more stable tests.
- Use Chrome DevTools Protocol (CDP) commands via
browser.executeCdpCommandto monitor download events directly.
Troubleshooting
If downloads do not appear in the target directory:
- Verify Chrome options are applied by logging
await browser.getCapabilities()and checking thegoog:chromeOptionssection. - Check file permissions on the download directory — ensure Chrome has write access.
- Test in headed mode first (
--headless=newremoved) to confirm the download works outside headless restrictions. - Inspect browser console logs for CORS, network errors, or failed requests to the file endpoint.
- Ensure the Angular app triggers the download via a direct URL or
blob:URL correctly handled by the browser. - If using
window.open()oriframe-based downloads, consider switching toanchorelements withdownloadattributes for better automation support.
Frequently Asked Questions
Why don't file downloads work in headless Chrome by default?
Headless Chrome disables certain UI features and security prompts. Without explicit preferences, it blocks or cancels downloads to prevent unintended behavior during automation.
Can I capture downloaded file content without saving to disk?
Not directly in E2E tests. The browser sandbox prevents access to raw download streams. Saving to disk and reading the file is the standard reliable method.
Do I need to use Protractor specifically?
No. This method works with any WebDriver-based framework (e.g., WebdriverIO, Cypress with custom Chrome arguments) that allows Chrome option configuration.
How do I handle downloads from iframes?
Ensure the iframe’s origin allows downloads and that Chrome preferences apply to all frames. Test navigation into the iframe context and trigger the download from there.
Are there security risks in enabling file downloads in tests?
Only if downloading from untrusted sources. Always mock or use local endpoints in E2E tests to avoid executing malicious content.
Can I test download buttons that use JavaScript to generate files?
Yes, as long as the final action triggers a browser download. Use Object.assign(document.createElement('a')) patterns with click() and download attributes, which are automation-friendly.