Mocking- A guide to mock jQuery ajax using Jest

This is my personal favourite tip from the collection. In almost every project, we used an ajax call. Ajax testing is difficult because it is dependent on an external source. In this example, I’ll show you how to use jest to test JQuery ajax.

const APP = (() => {
  var userData = null;
  const myURL = "http://stackoverflow.com";
  const getData = () => {
    $.ajax({
      type: "GET",
      url: myURL,
      success: obj.handleSuccess,
      error: obj.handleError,
    });
  };
  const handleError = () => {
    console.log("ERROR");
  };
  const handleSuccess = (data) => {
    userData = data;
    console.log(userData);
  };
  const render = () => {
    return "<div>some stuff</div>";
  };
  const obj = {
    getData,
    handleError,
    handleSuccess,
    render,
  };
  return obj;
})();
module.exports = APP;


const APP = require("../ajax");
describe("Ajax", () => {
  beforeEach(() => {
    jest.restoreAllMocks();
  });
  it("Data should load", () => {
    const ajaxSpy = jest.spyOn($, "ajax");
    APP.getData();
    expect(ajaxSpy).toBeCalledWith({
      type: "GET",
      url: "http://stackoverflow.com",
      success: expect.any(Function),
      error: expect.any(Function),
    });
  });
  it("should handle success", () => {
    const mUser = { userId: 1 };
    const logSpy = jest.spyOn(console, "log");
    APP.handleSuccess(mUser);
    expect(logSpy).toBeCalledWith(mUser);
  });
  it("should handle error", () => {
    const logSpy = jest.spyOn(console, "log");
    APP.handleError();
    expect(logSpy).toBeCalledWith("ERROR");
  });
});

You can also apply the same technique for other ajax libraries like node-fetch or inbuilt browser fetch API to test the application.

Please do not post any spam link in the comment box😊

إرسال تعليق (0)
أحدث أقدم