2012-01-11 12 views
58

当我运行我的测试时,我收到了上述错误消息。下面是我的代码(我使用Backbone JS和Jasmine进行测试)。有谁知道为什么发生这种情况?Sinon JS“试图包装已包装的AJAX”

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

回答

88

您必须在每次测试后删除间谍。看看的例子从兴农文档:

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

在我的考验之一,我有一个afterEach块太多,但它并没有解决问题。难道是因为我把afterEeach放在所有的测试之后,而不是beforeEach之后? – 2012-01-11 20:26:12

+0

我这么认为,导致'beforeEach'和'afterEach'函数调用就像你的测试一样。因此,在所有测试之后调用'afterEach'都不会起作用。 – 2012-01-11 20:30:33

+0

process.exit.restore(); ...不错 – danday74 2017-04-06 04:07:31

6

你在一开始就需要的是:

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

    afterEach -> 
    sandbox.restore() 

然后调用类似于:

windowSpy = sandbox.spy windowService, 'scroll' 
  • 请注意,我使用咖啡脚本。
+5

除非开放式或未指定,答案应该是问题所在的语言。 – 2017-01-09 08:35:10

+0

@JustinJohnson我不认为JS和咖啡脚本之间有任何误解。顺便说一句,他们是同一种语言。 – Winters 2017-01-10 04:39:00

+4

你的经验和提问者的经验不一样,你不应该假设他们是。 CoffeeScript为JavaScript添加了语法糖(这里你使用了),所以它们不是*同一个东西。 – 2017-01-11 05:04:19