诗乃不解开间谍

时间:2019-12-21 01:38:13

标签: jquery unit-testing mocking sinon

使用Mocha运行以下代码时,这两个测试均出错。

第一个返回:

  

“在每个之前”钩子应检查jQuery.getJSON对jQuery.ajax的使用情况TypeError:尝试包装已包装的ajax

第二个返回的只是失败的测试:

  

AssertError:预期ajax被调用一次,但被调用0次


var sinonAssert = require('@sinonjs/referee').assert;
var chaiAssert = require("chai").assert;

function makeCall(){
    $.ajax({
        method: "POST",
        url: "some.php",
        data: { name: "John", location: "Boston" },
        dataType: "application/json"
      })
        .done(function( msg ) {
          alert( "Data Saved: " + msg );
        });
}
describe('wrapping a function in a spy', function() {
    beforeEach(function() {        
        sinon.spy(jQuery, "ajax");
    });
    afterEach(function() {
        sinon.restore();
    });
    it("should inspect jQuery.getJSON's usage of jQuery.ajax", function(){        
        jQuery.getJSON("/some/resource");
        sinonAssert(jQuery.ajax.calledOnce);
        chaiAssert.strictEqual("/some/resource", jQuery.ajax.getCall(0).args[0].url);
        chaiAssert.strictEqual("json", jQuery.ajax.getCall(0).args[0].dataType);
    });
});
describe('makeCall', function() {
    const spy = sinon.spy(jQuery, "ajax");
    beforeEach(function() {
        makeCall();
    });
    afterEach(function() {
        sinon.restore();
    });
    it("should make only one ajax call", function(){
        sinon.assert.callCount(spy, 1);
    });
});

我希望每次测试后运行sinon.restore();都会解开jQuery对象。有趣的是,当我添加单独的沙箱时,第二个测试通过:

var sinonAssert = require('@sinonjs/referee').assert;
var chaiAssert = require("chai").assert;
var sandbox = require('sinon').createSandbox();
var sandbox2 = require('sinon').createSandbox();

function makeCall(){
    $.ajax({
        method: "POST",
        url: "some.php",
        data: { name: "John", location: "Boston" },
        dataType: "application/json"
      })
        .done(function( msg ) {
          alert( "Data Saved: " + msg );
        });
}
describe('wrapping a function in a spy', function() {
    beforeEach(function() {        
        sandbox.spy(jQuery, "ajax");
    });
    afterEach(function() {
        sandbox.restore();
    });
    it("should inspect jQuery.getJSON's usage of jQuery.ajax", function(){        
        jQuery.getJSON("/some/resource");
        sinonAssert(jQuery.ajax.calledOnce);
        chaiAssert.strictEqual("/some/resource", jQuery.ajax.getCall(0).args[0].url);
        chaiAssert.strictEqual("json", jQuery.ajax.getCall(0).args[0].dataType);
    });
});
describe('makeCall', function() {
    const spy = sandbox2.spy(jQuery, "ajax");
    beforeEach(function() {
        makeCall();
    });
    afterEach(function() {
        sandbox2.restore();
    });
    it("should make only one ajax call", function(){
        sandbox2.assert.callCount(spy, 1);
    });
});

为什么在测试后jQuery对象仍然保持包裹状态?

0 个答案:

没有答案