Sinon JS"试图包装已经包裹的ajax"

Tri*_*ong 65 testing backbone.js jasmine sinon

我运行测试时收到上述错误消息.下面是我的代码(我使用Backbone JS和Jasmine进行测试).有谁知道为什么会这样?

$(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();
     }
  })
}
Run Code Online (Sandbox Code Playgroud)

And*_*rle 97

你必须在每次测试后删除间谍.看一下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);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以在你的茉莉花测试中应该看起来像这样:

$(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();
     }
  })
}
Run Code Online (Sandbox Code Playgroud)


Win*_*ers 9

你最开始需要的是:

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

  afterEach ->
    sandbox.restore()
Run Code Online (Sandbox Code Playgroud)

然后打电话给:

windowSpy = sandbox.spy windowService, 'scroll'
Run Code Online (Sandbox Code Playgroud)
  • 请注意我使用咖啡脚本.

  • 除非是开放式的或未指明的,否则答案应该是问题所在的语言. (9认同)
  • 你的经验和提问者的经历是不一样的,你不应该认为它们是.CoffeeScript为JavaScript(你在这里使用)添加了语法糖,所以它们不是*同一个东西. (6认同)