How to Test URL Clicks with Karma, Mocha & Headless Chrome
In this article
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
- 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 installkarma-sourcemap-loaderif you want source maps. - Create a Karma configuration file – Generate
karma.conf.jsusingnpx karma initor manually. Set the framework tomocha, the browsers toChromeHeadless, and pointfilesto your test entry file. - Configure headless Chrome – In
karma.conf.js, add a custom launcher:customLaunchers: { ChromeHeadlessNoSandbox: { base: 'ChromeHeadless', flags: ['--no-sandbox', '--disable-gpu'] } }and setbrowsers: ['ChromeHeadlessNoSandbox']if you're in a CI environment without a sandbox. - Set up webpack preprocessor – If your code uses ES modules or JSX, add
webpacktopreprocessorsand provide a minimal webpack config inside the Karma file. This compiles your source and tests. - Write a test file – Create
test/url-click.spec.js. Use Mocha'sdescribeanditblocks. Inside the test, create a DOM element that triggers a click, and spy onwindow.locationor use a mock to capture the URL. - Simulate the click – Use
document.querySelector('a').click()or dispatch aMouseEvent. To prevent actual navigation, callevent.preventDefault()in your application code or stubwindow.location.assignbefore the click. - 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'). - Run the tests – Execute
npx karma start --single-runto run once. You should see output in the terminal showing pass/fail status. - Integrate with npm scripts – Add
"test": "karma start --single-run"to yourpackage.jsonfor 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
basePathmust 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.locationdirectly – In headless Chrome, settingwindow.locationcan cause the browser to attempt a real navigation. Always stub it. - Not cleaning up spies – Use
sinonortest.stuband restore them after each test to avoid cross-test contamination.
Tips
- Use
beforeEachto set up a fresh DOM and stubs, andafterEachto 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
donecallback or return a promise. - Use
karma-coverageto see which parts of your code are tested. - In CI, add
--single-runto 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.