User Agents

Web browsers and everyday web tech, explained

Fix Missing Global Functions in Jasmine with Headless Chrome

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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 defined or setTimeout is not a function. Note the exact function name and context.
  2. Verify the test environment setup: Confirm that your testing framework (e.g., Karma) is launching Chrome in headless mode correctly. In Karma, ensure the browsers array includes ChromeHeadless or a custom launcher with the proper flags.
  3. Check for polyfills or shims: Some globals like fetch are not available in older or minimal Chrome environments. Install a polyfill like whatwg-fetch using npm: npm install --save-dev whatwg-fetch.
  4. Load polyfills before tests: In your test configuration, ensure the polyfill is loaded before any specs. For Karma, add it to the files array in karma.conf.js:
    files: [
      'node_modules/whatwg-fetch/dist/fetch.umd.js',
      'src/**/*.js',
      'spec/**/*.js'
    ],
    This ensures fetch is available globally.
  5. Expose globals manually if needed: If a global is undefined (e.g., __DEV__ or ENV), define it in a helper file. Create spec/helpers/global-setup.js with:
    Object.defineProperty(window, '__DEV__', {
      value: true,
      writable: true,
      configurable: true
    });
    Then include this file in your test suite before specs run.
  6. Use Karma's beforeEach or environment injection: For Karma, use the client configuration to inject globals:
    client: {
      globals: {
        __DEV__: true
      }
    }
    This makes the global available during test execution.
  7. Ensure proper context for setTimeout and setInterval: While these are usually available, headless environments may sandbox them. Avoid stubbing them unless testing timing logic. If using Jasmine spies, restore with spyOn and and.callThrough() to preserve original behavior.
  8. 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.
  9. 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 puppeteer or chromedriver to manage versions.
  10. Validate with a minimal test case: Create a simple spec that only checks for the global’s presence:
    it('should have fetch available', function() {
      expect(typeof fetch).toBe('function');
    });
    Run this in headless mode to confirm the fix.

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, or WebSocket are present without verification.
  • Using Node.js globals in browser context: Variables like process or __dirname are 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.defineProperty with configurable: false only when necessary, and always test the side effects.

Tips

  • Use globalThis for cross-environment globals: Instead of window.fetch, use globalThis.fetch to 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.userAgent and typeof fetch to verify the runtime environment.

Troubleshooting

If global functions are still missing after following the steps:

  • Check file load order: In Karma, the files array order matters. Ensure polyfills and helpers are listed before spec files.
  • Verify Chrome flags: Some flags like --disable-web-security or --no-sandbox can affect API availability. Use minimal flags unless required.
  • Inspect the browser console: Use --remote-debugging-port=9222 to 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.