如何在';窗口。打开';(javascript)使用sinon

如何在';窗口。打开';(javascript)使用sinon,javascript,sinon,window.open,Javascript,Sinon,Window.open,这是我必须测试的代码: myFunction: function(data) { var file = new Blob(data, {type: 'text/plain'}); window.open(window.URL.createObjectURL(file)); } 为了测试它,我想通过以下方式测试window.open函数是否被调用,在window.open上应用“spy”: sandbox.spy(window, 'open'); 但是,即使将前一行作为

这是我必须测试的代码:

myFunction: function(data) {
    var file = new Blob(data, {type: 'text/plain'});
    window.open(window.URL.createObjectURL(file));
}
为了测试它,我想通过以下方式测试window.open函数是否被调用,在window.open上应用“spy”:

    sandbox.spy(window, 'open');
但是,即使将前一行作为测试中的唯一行,我只得到测试失败和以下消息:

检测到全局泄漏:控制台记录,打开

因此,为了避免这种情况,我尝试以这种方式在测试中重新定义函数:

     global.window = {
           open: function (url) {}
     };
在这种情况下,会引发异常:

试图分配给只读属性

然后,我试图通过以下方式模拟“开放”:

sandbox.mock(window, 'open');
objectUnderTest.myFunction();
expect(window.open.callCount).to.equal(1);
这样,我就不会得到全局或只读错误,但“expect”上有一个异常,告诉我:

预期未定义为等于1


是否有人知道成功测试window.open的方法?

以下是基于
Node.js
环境的单元测试解决方案:

index.js

const obj={
myFunction:函数(数据){
var file=newblob(数据,{type:'text/plain'});
open(window.URL.createObjectURL(文件));
}
};
module.exports=obj;
index.spec.js

const obj=require('./');
const sinon=要求(“sinon”);
const{expect}=require('chai');
描述('53524524',()=>{
之前(()=>{
类Blob{}
global.Blob=Blob;
全局窗口={
open(){},
网址:{
createObjectURL(){}
}
};
});
它('应该正确地测试myFunction',()=>{
const openStub=sinon.stub(窗口“打开”);
const createObjectURLStub=sinon.stub(global.window.URL,'createObjectURL')。返回('伪对象URL');
对象myFunction(“假数据”);
expect(createObjectURLStub.calledOnce).to.be.true;
expect(openStub.calledWith('fake object url')).to.be.true;
});
});
单元测试结果和覆盖率报告:


53524524
✓ 应该正确地测试myFunction吗
1次通过(11毫秒)
---------------|----------|----------|----------|----------|-------------------|
文件|%Stmts |%Branch |%Funcs |%Line |未覆盖行|s|
---------------|----------|----------|----------|----------|-------------------|
所有文件| 100 | 100 | 66.67 | 100 ||
index.js | 100 | 100 | 100 | 100 ||
index.spec.js | 100 | 100 | 60 | 100 ||
---------------|----------|----------|----------|----------|-------------------|

源代码:

您使用的是什么测试框架?