首页 > 解决方案 > 如何使用 sinon 对“window.open”(javascript)进行单元测试

问题描述

这是我必须测试的代码:

myFunction: function(data) {
    var file = new Blob(data, {type: 'text/plain'});
    window.open(window.URL.createObjectURL(file));
}

为了测试它,我想测试是否调用了 window.open 函数,在 window.open 上应用“间谍”,方法如下:

    sandbox.spy(window, 'open');

但是,即使将前一行作为测试中的唯一行,我只得到测试失败和以下消息:

检测到全局泄漏:consoleLogging,打开

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

     global.window = {
           open: function (url) {}
     };

在这种情况下会引发异常:

试图分配给只读属性

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

sandbox.mock(window, 'open');
objectUnderTest.myFunction();
expect(window.open.callCount).to.equal(1);

这样,我没有得到全局或只读错误,但“预期”出现异常,告诉您:

预期未定义等于 1

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

标签: javascriptsinonwindow.open

解决方案


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

index.js

const obj = {
  myFunction: function(data) {
    var file = new Blob(data, { type: 'text/plain' });
    window.open(window.URL.createObjectURL(file));
  }
};

module.exports = obj;

index.spec.js

const obj = require('./');
const sinon = require('sinon');
const { expect } = require('chai');

describe('53524524', () => {
  before(() => {
    class Blob {}
    global.Blob = Blob;
    global.window = {
      open() {},
      URL: {
        createObjectURL() {}
      }
    };
  });
  it('should test myFunction correctly', () => {
    const openStub = sinon.stub(window, 'open');
    const createObjectURLStub = sinon.stub(global.window.URL, 'createObjectURL').returns('fake object url');
    obj.myFunction('fake data');
    expect(createObjectURLStub.calledOnce).to.be.true;
    expect(openStub.calledWith('fake object url')).to.be.true;
  });
});

带有覆盖率报告的单元测试结果:


  53524524
    ✓ should test myFunction correctly


  1 passing (11ms)

---------------|----------|----------|----------|----------|-------------------|
File           |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files      |      100 |      100 |    66.67 |      100 |                   |
 index.js      |      100 |      100 |      100 |      100 |                   |
 index.spec.js |      100 |      100 |       60 |      100 |                   |
---------------|----------|----------|----------|----------|-------------------|

源码:https ://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/53524524


推荐阅读