65 votes

Sinon JS "Attempted to wrap ajax which is already wrapped" (Tentative d'envelopper un ajax déjà enveloppé)

J'ai obtenu le message d'erreur ci-dessus lorsque j'ai exécuté mon test. Voici mon code (j'utilise Backbone JS et Jasmine pour les tests). Quelqu'un sait-il pourquoi cela se produit ?

$(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();
     }
  })
}

99voto

Andreas Köberle Points 16453

Vous devez retirer l'espion après chaque test. Regardez l'exemple dans la documentation du sinon :

{
    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);
    }
}

Ainsi, dans votre test jasmine devrait ressembler à ceci :

$(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();
     }
  })
}

9voto

Winters Points 423

Ce dont vous avez besoin au tout début, c'est :

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

  afterEach ->
    sandbox.restore()

Puis appelez quelque chose comme :

windowSpy = sandbox.spy windowService, 'scroll'
  • Veuillez noter que j'utilise le café script.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X