Fix Missing Global Functions in Jasmine with Headless Chrome
In this article
Fixing missing global functions in Jasmine with headless Chrome ensures your unit tests run reliably in automated environments like CI/CD pipelines. When Jasmine runs in headless Chrome—commonly via tools like Karma or Puppeteer—certain global functions (such as setTimeout, fetch, or custom globals) may not be available or behave differently than in a full browser. This guide walks through diagnosing and resolving these issues so your tests execute consistently.
What You'll Need
- A working Jasmine test suite
- Headless Chrome configured (typically via Karma, Puppeteer, or a testing framework like Jest with Chrome emulation)
- Access to your test configuration files (e.g.,
karma.conf.js,spec/helpers, or test setup scripts) - Basic familiarity with JavaScript and browser environments
Step-by-Step
- Identify the missing global function: Run your Jasmine tests in headless Chrome and check the console or test output for errors like
ReferenceError: fetch is not definedorsetTimeout is not a function. Note the exact function name and context. - Verify the test environment setup: Confirm that your testing framework (e.g., Karma) is launching Chrome in headless mode correctly. In Karma, ensure the
browsersarray includesChromeHeadlessor a custom launcher with the proper flags. - Check for polyfills or shims: Some globals like
fetchare not available in older or minimal Chrome environments. Install a polyfill likewhatwg-fetchusing npm:npm install --save-dev whatwg-fetch. - Load polyfills before tests: In your test configuration, ensure the polyfill is loaded before any specs. For Karma, add it to the
filesarray inkarma.conf.js:
This ensuresfiles: [ 'node_modules/whatwg-fetch/dist/fetch.umd.js', 'src/**/*.js', 'spec/**/*.js' ],fetchis available globally. - Expose globals manually if needed: If a global is undefined (e.g.,
__DEV__orENV), define it in a helper file. Createspec/helpers/global-setup.jswith:
Then include this file in your test suite before specs run.Object.defineProperty(window, '__DEV__', { value: true, writable: true, configurable: true }); - Use Karma's
beforeEachor environment injection: For Karma, use theclientconfiguration to inject globals:
This makes the global available during test execution.client: { globals: { __DEV__: true } } - Ensure proper context for
setTimeoutandsetInterval: While these are usually available, headless environments may sandbox them. Avoid stubbing them unless testing timing logic. If using Jasmine spies, restore withspyOnandand.callThrough()to preserve original behavior. - Test in both headless and non-headless modes: Run your suite in regular Chrome and headless Chrome to confirm consistency. Differences may reveal missing globals or environment assumptions.
- Update Chrome and drivers: Ensure you're using a recent version of Chrome and ChromeDriver. Older versions may lack support for modern APIs. Use
npm install puppeteerorchromedriverto manage versions. - Validate with a minimal test case: Create a simple spec that only checks for the global’s presence:
Run this in headless mode to confirm the fix.it('should have fetch available', function() { expect(typeof fetch).toBe('function'); });
Common Mistakes
- Loading polyfills after specs: If a polyfill script is listed after your test files, the global may not be defined in time. Always load polyfills first.
- Assuming all globals are available: Headless Chrome may disable certain APIs for security or performance. Never assume
localStorage,fetch, orWebSocketare present without verification. - Using Node.js globals in browser context: Variables like
processor__dirnameare Node-specific and will be undefined in Chrome. Avoid them in browser-based tests. - Overwriting globals unintentionally: Some test helpers or libraries may redefine globals. Use
Object.definePropertywithconfigurable: falseonly when necessary, and always test the side effects.
Tips
- Use
globalThisfor cross-environment globals: Instead ofwindow.fetch, useglobalThis.fetchto access globals in a way that works across environments. - Centralize global setup: Keep all global definitions in a single helper file loaded at startup. This makes debugging and maintenance easier.
- Mock only what you need: Avoid stubbing real globals unless testing specific behaviors. Preserving native functionality reduces false positives.
- Log environment details: Add a debug spec that logs
navigator.userAgentandtypeof fetchto verify the runtime environment.
Troubleshooting
If global functions are still missing after following the steps:
- Check file load order: In Karma, the
filesarray order matters. Ensure polyfills and helpers are listed before spec files. - Verify Chrome flags: Some flags like
--disable-web-securityor--no-sandboxcan affect API availability. Use minimal flags unless required. - Inspect the browser console: Use
--remote-debugging-port=9222to attach DevTools to headless Chrome and check for runtime errors. - Test polyfill compatibility: Some polyfills require specific versions of Chrome. Check the polyfill’s documentation for supported environments.
- Isolate the issue: Run a single spec file with only the global check to rule out interference from other tests or setup code.
Frequently Asked Questions
Why is fetch not defined in headless Chrome?
Older versions of headless Chrome or environments without full DOM support may not include fetch. Use the whatwg-fetch polyfill to add it.
Can I use global like in Node.js?
No. In browser environments, use window or globalThis. The global object is Node-specific.
How do I stub a global function without breaking tests?
Use Jasmine’s spyOn(window, 'fetch') and call and.callThrough() to allow real behavior unless you’re testing failure cases.
Does headless Chrome support localStorage?
Yes, but it’s sandboxed per page session. Clear it manually in beforeEach if tests depend on clean state.
Why do my tests pass in Chrome but fail in headless mode?
Differences in API availability, timing, or sandboxing can cause this. Always test in both modes and avoid environment-specific assumptions.
Can I define globals dynamically during tests?
Yes, but define them early. Use helper files or configuration hooks to set them before specs run.