User Agents

Web browsers and everyday web tech, explained

How to Test URL Clicks with Karma, Mocha & Headless Chrome

· 4 min read · How the Web Works

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

Testing URL clicks in a front-end application ensures that navigation and link handling work correctly without a real browser. This guide shows you how to set up Karma with Mocha and headless Chrome to automate click tests, verify that the right URL is requested, and catch regressions early. You'll need a Node.js project with npm installed, and a basic understanding of JavaScript testing.

What You'll Need

  • Node.js (v14 or later)
  • npm or yarn
  • An existing front-end project (or a simple one to practice on)
  • Basic knowledge of Mocha and Karma

Step-by-Step

  1. Install dependencies – Run npm install --save-dev karma karma-mocha mocha karma-chrome-launcher karma-webpack webpack webpack-cli (if using webpack) or adjust to your module bundler. Also install karma-sourcemap-loader if you want source maps.
  2. Create a Karma configuration file – Generate karma.conf.js using npx karma init or manually. Set the framework to mocha, the browsers to ChromeHeadless, and point files to your test entry file.
  3. Configure headless Chrome – In karma.conf.js, add a custom launcher: customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox', '--disable-gpu'] } } and set browsers: ['ChromeHeadlessNoSandbox'] if you're in a CI environment without a sandbox.
  4. Set up webpack preprocessor – If your code uses ES modules or JSX, add webpack to preprocessors and provide a minimal webpack config inside the Karma file. This compiles your source and tests.
  5. Write a test file – Create test/url-click.spec.js. Use Mocha's describe and it blocks. Inside the test, create a DOM element that triggers a click, and spy on window.location or use a mock to capture the URL.
  6. Simulate the click – Use document.querySelector('a').click() or dispatch a MouseEvent. To prevent actual navigation, call event.preventDefault() in your application code or stub window.location.assign before the click.
  7. Assert the URL – After the click, check that the expected URL was passed to the navigation function. For example: expect(window.location.assign).to.have.been.calledWith('/contact').
  8. Run the tests – Execute npx karma start --single-run to run once. You should see output in the terminal showing pass/fail status.
  9. Integrate with npm scripts – Add "test": "karma start --single-run" to your package.json for easy running.

Common Mistakes

  • Forgetting to stub navigation – If you don't prevent default or stub location, the test will try to navigate the headless browser and fail or hang.
  • Not setting the correct base path – Karma's basePath must be set so that files are served correctly. Usually set to '' or the project root.
  • Missing webpack config – If you use ES modules, Babel, or TypeScript, the test files won't load without the webpack preprocessor.
  • Using window.location directly – In headless Chrome, setting window.location can cause the browser to attempt a real navigation. Always stub it.
  • Not cleaning up spies – Use sinon or test.stub and restore them after each test to avoid cross-test contamination.

Tips

  • Use beforeEach to set up a fresh DOM and stubs, and afterEach to restore them.
  • If you're testing multiple links, loop over an array of expected URLs to keep tests DRY.
  • For async navigation (e.g., after a fetch), use Mocha's done callback or return a promise.
  • Use karma-coverage to see which parts of your code are tested.
  • In CI, add --single-run to avoid the test runner staying alive.

Troubleshooting

Test fails with “ChromeHeadless not found” – Ensure you have Chrome installed and the karma-chrome-launcher package. If in a Linux CI, use the --no-sandbox flag as shown.

Webpack errors – Check that your webpack config in Karma is correct. You may need to set mode: 'development' and devtool: 'inline-source-map'.

Tests pass but no output – Make sure your test files are included in the files array. Use pattern: 'test/**/*.spec.js'.

Click doesn't trigger – Ensure the element is in the DOM. Use document.body.innerHTML = 'link' in beforeEach.

Navigation happens anyway – Add event.preventDefault() in your app's click handler, or stub window.location.assign before the click.

Frequently Asked Questions

Can I test clicks on real URL without stubbing?

It's possible but not recommended because the headless browser will attempt to load the page, which slows tests and may cause cross-origin issues. Stubbing is faster and more reliable.

How do I test anchor tags that use target="_blank"?

Stub window.open instead of location.assign. Then assert that window.open was called with the expected URL.

Can I use Karma with other test frameworks?

Yes, Karma supports Jasmine, QUnit, and others. For Mocha, you need the karma-mocha adapter.

How do I run tests in a real Chrome browser instead?

Change the browsers array to ['Chrome']. You can also run both headless and headed in parallel.

Why do my tests fail when using ES modules?

Karma doesn't natively support ES modules. Use webpack or another bundler to transpile them. Alternatively, use the karma-esbuild plugin.

Can I test URL clicks in an Angular or React component?

Yes, but you'll need to set up the component's testing utilities (e.g., Angular's TestBed or React Testing Library) and then simulate the click on the rendered element.