65

我在运行测试时收到了上述错误消息。下面是我的代码(我使用 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();
     }
  })
}
4

2 回答 2

99

您必须在每次测试后删除间谍。看一下 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);
    }
}

所以在你的茉莉花测试中应该是这样的:

$(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();
     }
  })
}
于 2012-01-11T20:21:32.753 回答
9

一开始你需要的是:

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

  afterEach ->
    sandbox.restore()

然后调用类似的东西:

windowSpy = sandbox.spy windowService, 'scroll'
  • 请注意我使用的是咖啡脚本。
于 2015-10-21T03:25:18.110 回答