# jquery-mockjax: intercepting $.ajax() calls to test jQuery front-end code without a backend

> jquery-mockjax replaces jQuery's $.ajax() method with its own interceptor, matching registered mock handlers against each request and returning fake responses in place of real network calls. Version 3.0.1 is current, and the README warns of major breaking changes from v2.

**jakerella/jquery-mockjax** — The jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses

- Repository: https://github.com/jakerella/jquery-mockjax
- Stars: 2,083 · Forks: 366
- Language: JavaScript
- License: NOASSERTION
- Published: 2026-10-11 · Updated: 2026-10-11 · Language: en
- Canonical page: https://hysenlabs.com/projects/jakerella-jquery-mockjax

## Intercepting $.ajax() to test front-end code without a live backend

jquery-mockjax works by replacing jQuery's own $.ajax() method with a custom interceptor at the jQuery level rather than at the XMLHttpRequest level. Every call to $.ajax() in the application code then passes through Mockjax, which compares the request against registered mock handlers. When a match is found, Mockjax returns the configured fake response instead of executing a real network request. The README is explicit about scope: this is a tool for testing front-end code without a server and is not intended for use in a production environment.

Developers who write jQuery-based front-end code and test with tools like QUnit benefit from this approach because isolating ajax-dependent functions requires no real backend at all. The interception happens at the jQuery level, not at the browser XMLHttpRequest level, which keeps setup minimal for projects already using jQuery but means projects calling XMLHttpRequest directly or using fetch are outside the library's scope.

## $.mockjax() registers handlers and $.ajax() becomes a Mockjax call from that point

Mockjax adds $.mockjax() to the window object's jQuery instance and rewrites $.ajax() in place. From the moment the library is loaded, every $.ajax() call goes through Mockjax, whether or not a handler matches. Each $.mockjax() call registers a handler, and registered handlers are compared against each request in the order they were added.

The MockHandler object and its options are documented in the README's table of contents, along with a MockjaxRequestSettings object that covers request-side configuration. A global match order setting controls which handler applies when multiple ones could respond to the same request. Managing the set of registered handlers is covered under Managing Mockjax Data in the README, and public API methods beyond $.mockjax() itself are documented under Public API Methods.

## Installing from npm and registering the first mock handler

The package is available from npm under the name jquery-mockjax. For script-tag usage, include dist/jquery.mockjax.js in the test file. The module entry point for bundled setups is src/attach.mjs. The README recommends registering mocks before test cases run.

Here is the minimal handler from the README: a mock that returns a fixed array when the application requests /api/products:

```javascript
$.mockjax({
  url: '/api/products',
  responseText: [
    { id: 13, name: 'rubber duck' },
    { id: 42, name: 'house plant' }
  ]
})
```

With that registered, any $.ajax('/api/products') in the test run receives the two-item array instead of a real HTTP response. The responseText property accepts a JavaScript object or a JSON string interchangeably. A full QUnit example in the README wires this to an application function and uses an onAfterSuccess callback to run assertions after the success path of $.ajax() completes.

## Four matching dimensions: URL, request data, headers and HTTP method

URL matching is the most common case, and the README dedicates a section to it separately from data and header matching, because URL patterns support more than exact string matching. A handler can also match on the data sent with a request, on specific request headers, and on the HTTP method (GET, POST, and so on). All specified criteria must match for the handler to fire.

When multiple handlers could match a single request, a global setting controls which one takes precedence. For tests that register several handlers covering overlapping URLs, that setting avoids ambiguity. A separate section on Registering Multiple Handlers in the README addresses this case specifically.

Proxy support is covered as a response strategy that forwards to a real URL rather than returning a fixed value. Dynamic response functions let a handler compute its response, and URL parameter capturing passes matched URL segments into that function.

## A variable name mismatch in the README's QUnit example would break the test as written

The QUnit example in the Core Principles section of the README defines a variable named items with a plural 's' to hold the result of $('ul.products li'). Two lines later, the assertions reference item without the 's': assert.equal(item[0].text(), 'rubber duck', ...) and assert.equal(item[0].attr('id'), 'item-13', ...). Since item is never declared in that code block, running those assertions exactly as written would throw a ReferenceError.

The intent is clear from context: item should be items. This typo is in the first full code example a developer encounters when reading the README sequentially, and it shows up in a section whose purpose is to establish the pattern for using the library. Copying the test code directly would produce a broken test, not a passing one.

## Latency simulation, dynamic responses, JSONP and custom logging in the advanced API

Response time and latency simulation are documented under Simulating Response Time and Latency, allowing tests to exercise slow-path code. HTTP response status codes can be set to trigger the error callback rather than success, and server timeouts can be forced to test timeout-handling branches.

Dynamic response functions replace static responseText with a function that computes the response at request time. URL parameter capturing feeds matched URL segments into that function, enabling parameterized responses. JSONP mocking appears as a subsection under Using Other Data Types, and the README notes a proxy strategy where the handler forwards to a real URL rather than generating its own response.

Logging is configurable: a custom logger can replace the default one, which is useful for suppressing output in test runs that would otherwise print Mockjax diagnostics. A global URL namespace setting applies a prefix to all registered handlers at once to avoid repeating a shared path prefix in every $.mockjax() call.

## What build:dist validates before publication, and a discrepancy in the repository metadata

The build:dist script in package.json runs the full validation chain before publication: style check, lint, coverage measurement, webpack build, integration tests across all jQuery versions, Node.js tests and RequireJS tests in sequence. Version 3.0.1 was published on 2026-05-07 and the last push was on 2026-10-01.

A discrepancy is visible before adoption: the repository metadata shows the licence as unrecognized by GitHub's automated classifier while package.json declares MIT, so reading the LICENSE file at the repository root is needed to confirm which terms apply. The CONTRIBUTING.md file at the root covers the development workflow for contributors who want to modify the library.

## Conclusion

jquery-mockjax suits front-end developers who test jQuery-dependent code calling $.ajax() and want a direct mock without running any backend at all. It does not suit projects that have replaced jQuery with native fetch or axios, since $.mockjax() only intercepts $.ajax() calls and nothing else. Before adopting, check that your jQuery version is supported by consulting the jQuery Version Support section in the documentation, and read the README's warning about major breaking changes if you are coming from the v2 API.

## FAQ

### How do I install jquery-mockjax?

Install it from npm as jquery-mockjax. For script-tag usage, include dist/jquery.mockjax.js in the test file. For bundled setups, the module entry is src/attach.mjs.

### Can jquery-mockjax intercept fetch or XMLHttpRequest calls?

No. jquery-mockjax replaces jQuery's $.ajax() and only intercepts calls made through that method. Fetch and direct XMLHttpRequest usage are outside its scope.

### Can jquery-mockjax simulate slow network responses?

Yes. The README documents simulating response time and latency as a distinct feature, along with forced server timeout simulation for testing timeout-handling code paths.

### Does jquery-mockjax support matching on request data and headers?

Yes. A handler can match on the request data, on specific request headers and on the HTTP method, in addition to the URL. All specified criteria must match for the handler to fire.

### How does the onAfterSuccess callback work in jquery-mockjax?

The onAfterSuccess callback fires after the success callback in application source code, with the same arguments. The README's QUnit example uses it to run test assertions after the application's success path has executed.

## Sources

- [Issues](https://github.com/jakerella/jquery-mockjax/issues)
- [jakerella/jquery-mockjax on GitHub](https://github.com/jakerella/jquery-mockjax)
- [README](https://github.com/jakerella/jquery-mockjax/blob/master/README.md)
- [Releases](https://github.com/jakerella/jquery-mockjax/releases)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/jakerella-jquery-mockjax
