Sinon 警报存根:"Attempted to wrap alert which is already wrapped"

Sinon alert stub: "Attempted to wrap alert which is already wrapped"

我正在使用 Sinon 1.14。我想使用 Sinon 的存根来抑制所有 javascript 警报。

使用最新的 Chrome 版本:42.0.2311.135 m,出现异常:"Attempted to wrap alert which is already wrapped"

下面的代码在最新的 Firefox 中运行良好。我会更新 fiddle.

var hooks = {

    beforeEach: function(assert){
        this.sandbox = sinon.sandbox.create();
        this.sandbox.stub(window, 'alert', function (msg) { return false; });
    },

    afterEach: function(){
        this.sandbox.restore();
    }
};

module('example', hooks);

test('example', function(assert){
    ok(true, 'does not throw an exception');
});

window.alert 是一个全局函数。每次 beforeEach 运行时,它都会用包装函数替换该函数。我想 Sinon 会阻止你将一个函数包装两次。

您可以确保设置函数只运行一次。

或者修改您的代码,使您没有全局依赖性(即传递对 alert 或委派 window 对象的引用)。这会对您的代码架构产生很大影响。这也说明了为什么在设计架构时考虑测试很重要。

将 Sinon 从 1.14 更新到 1.14.1 似乎可以解决问题。我认为这是一个错误?

附带说明一下,代码在 1.12 中也能正常运行。