Sinon JS "Attempted to wrap ajax which is already wrapped"

Testingbackbone.jsJasmineSinon

Testing Problem Overview


I got the above error message when I ran my test. Below is my code (I'm using Backbone JS and Jasmine for testing). Does anyone know why this happens?

$(function() {
  describe("Category", function() {
     beforeEach(function() {
      category = new Category;
      sinon.spy(jQuery, "ajax");
     }

     it("should fetch notes", function() {
      category.set({code: 123});
      category.fetchNotes();
      expect(category.trigger).toHaveBeenCalled();
     }
  })
}

Testing Solutions


Solution 1 - Testing

You have to remove the spy after every test. Take a look at the example from the sinon docs:

{
    setUp: function () {
        sinon.spy(jQuery, "ajax");
    },

    tearDown: function () {
        jQuery.ajax.restore(); // Unwraps the spy
    },

    "test should inspect jQuery.getJSON's usage of jQuery.ajax": function () {
        jQuery.getJSON("/some/resource");

        assert(jQuery.ajax.calledOnce);
        assertEquals("/some/resource", jQuery.ajax.getCall(0).args[0].url);
        assertEquals("json", jQuery.ajax.getCall(0).args[0].dataType);
    }
}

So in your jasmine test should look like this:

$(function() {
  describe("Category", function() {
     beforeEach(function() {
      category = new Category;
      sinon.spy(jQuery, "ajax");
     }

     afterEach(function () {
        jQuery.ajax.restore();
     });

     it("should fetch notes", function() {
      category.set({code: 123});
      category.fetchNotes();
      expect(category.trigger).toHaveBeenCalled();
     }
  })
}

Solution 2 - Testing

What you need in the very beginning is:

  before ->
    sandbox = sinon.sandbox.create()

  afterEach ->
    sandbox.restore()

Then call something like:

windowSpy = sandbox.spy windowService, 'scroll'
  • Please notice that I use coffee script.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrivektorView Question on Stackoverflow
Solution 1 - TestingAndreas KöberleView Answer on Stackoverflow
Solution 2 - TestingWinters HuangView Answer on Stackoverflow