← Back to list

How to mock jqXHR with Jest

In the era of component-based rendering, jQuery is still in raw use in many projects, due to its simplicity and plain learning curve. In…

Hweemyoung · 2024-03-08 08:00 · 0 claps · 1.7 min read
#jest #xhr #javascript
Open on Medium ↗
Wiki topics: EDU · Education & Learning 🌐 · Web Development ✨ · Lifestyle · General

How to mock jqXHR with Jest

Photo by Greg Rakozy on Unsplash

Photo by Greg Rakozy on Unsplash

In the era of component-based rendering, jQuery is still in raw use in many projects, due to its simplicity and plain learning curve. In such projects, many QA teams are striving to mock jQuery to white-box test their modules.

And things often become cumbersome, when a tester wants to mock the behavior of AJAX, when module communicates through HTTP. Common use cases include mocking $.ajax.done and $.ajax.fail .

Because $.ajax() returns not jQuery object, mocking jQuery module isn’t simply enough. Here we have to provide mock implementation of function $.ajax manually.

Mocking $.ajax

Usually, we don’t want to mock every feature of AJAX but specific features. In that case, we still use our good jest.requireActual to keep the original AJAX in control.

For example, the following test code only mocks $.ajax.fail and leave other properties intact.

const {
  expect,
  test,
} = require('@jest/globals');
const req = {
  type: "POST",
  url: "http://foo.bar/baz",
  timeout: 10000,
  async: false,
  headers: { 'Content-Type': 'application/json;charset=utf8' },
  data: '{}',
  dataType: 'json',
}

jest.mock('jquery', () => {
  const actualJQ = jest.requireActual('jquery');
  return {
    __esModule: true, // (optional) Enable ES Module.
    ...actualJQ, // Load actual jQuery.
    ajax: jest.fn().mockImplementation((settings) => {
      var fakeJqxhr = actualJQ.ajax(settings); // Run actual .ajax.
      fakeJqxhr.fail = jest.fn().mockImplementation((jqXHR, textStatus, errorThrown) => {
        // Mock fakeJqxhr.fail by overwriting.
        console.log('FAKE fail...');
        return fakeJqxhr;
      });
      return fakeJqxhr;
    })
  }
});

$ = require('jquery');
test('Mocking jqXHR Partials', () => {
  var res = 'Neither .done nor .fail callback has been passed,';
  var jqxhr = $.ajax(req) // This ajax operation is to fail.
    .done((data) => {
      console.log('Done!');
      res += ' and passed .done callback!';
    }) // Callback will NOT be called because ajax fails.
    .fail((jqXHR, textStatus, errorThrown) => {
      console.error('Fail...');
      res += ' and passed .fail callback!';
    }) // Callback will NOT be called because $.ajax(...).fail has been mocked.
    .always((data, textStatus, jqXHR) => {
      console.info('Always.');
      res += ' and passed .always callback!';
    }); // Callback will be called because $.ajax(...).always is intact.
  expect(res).toBe('Neither .done nor .fail callback has been passed, and passed .always callback');
});

And test result is like:

PS C:\Users\fbcuser\git\Js> node "node_modules/jest/bin/jest.js"
"c:/Users/fbcuser/git/Js/base/MockFnTest.test.js" -t "Mocking jqXHR Partials"
  console.log
    FAKE fail...

      at Object.log (base/MockFnTest.test.js:87:105)

  console.info
    Always.

      at Object.info (base/MockFnTest.test.js:109:56)

PASS base/MockFnTest.test.js
  √ Mocking jqXHR Partials (1491 ms)

...

Ran all test suites matching /c:\\Users\\fbcuser\\git\\Js\\base\\MockFnTest.test.js/i with tests
matching "Mocking jqXHR Partials".

Now we successfully mocked only .fail method of jqXHR and other properties are intact!


메타데이터
post_id
12ce119f145e
slug
how-to-mock-jqxhr-with-jest-12ce119f145e
url
https://medium.com/@hweemyoung/how-to-mock-jqxhr-with-jest-12ce119f145e
canonical_url
https://medium.com/@hweemyoung/how-to-mock-jqxhr-with-jest-12ce119f145e
author_url
https://medium.com/@hweemyoung
status
ok
fetched_at
2026-07-24 07:01:26