Skip to content Skip to sidebar Skip to footer

How To Test Done Part Of Ajax In Jasmine

I really like this resource for AJAX in general and it works in terms of testing a success or error function that's within the AJAX parameters. However, when I instead choose to no

Solution 1:

Well, probably the example in the question is not the same you are running local, but it should fail in the line spyOn($, "ajax").and.callFake(deferred) because callFake expect a function and deferred is not. Instead, deferred should be a resolved Promise and use .and.returnValue instead of .and.callFake.

Here is a working example:

  function itWorked() {
    console.log("It worked!!");
  }

  function sendRequest(callbacks, configuration) {
    $.ajax({}).done(function(response) {
      itWorked();
    });
  }

  describe("Ajax Tests", () => {

    beforeEach(function() {
      spyOn(window, "itWorked").and.callThrough();
      deferred = $.Deferred().resolve(); // Call resolve
      spyOn($, "ajax").and.returnValue(deferred); // Use return value
      sendRequest();
    });

    it("should work", function() {
      expect($.ajax).toHaveBeenCalled(); // pass
      expect(window.itWorked).toHaveBeenCalled(); // pass
    });
  });

Note that I've added console.log("It worked!!"); and use .and.callThrough(); just to double check in the console that "It worked!!" was logged.

When calling $.Deferred().resolve() you can pass a mocked response to deal with in your .done or .then callback. Something like .resolve({ success: true }). Check an example here

Hope it helps


Post a Comment for "How To Test Done Part Of Ajax In Jasmine"