【问题标题】:How can `document.execCommand` be unit tested?`document.execCommand` 如何进行单元测试?
【发布时间】:2018-04-25 13:42:07
【问题描述】:

我正在尝试为类似文字处理器的操作编写单元测试,例如将列表应用于文本节点,但我发现document.execCommand 不适用于jsdom,所以我很难过我如何对以下操作进行单元测试:

document.getElementById('run').addEventListener('click', function() {
  document.execCommand("insertorderedlist");
});
<div contenteditable="true">Foo</div>
<button id="run">Select "Foo" then Click</button>

【问题讨论】:

  • 叛逆者,你搞定了吗?试图弄清楚我是否可以以某种方式模拟这个......
  • @Alexandra nop!

标签: mocha.js sinon jsdom


【解决方案1】:

我最终不得不明确地模拟 document.execCommand

// test-mocks.js
global.document.execCommand = function execCommandMock() { };

然后将我的模拟物直接喂入 mocha:

"specs": "mocha --require @babel/register --require jsdom-global/register --require ignore-styles --require test-mocks.js ./path/to/tests.spec.js"

【讨论】:

  • 我用 jest + react-testing-library 得到了同样的结果:在我的测试文件顶部添加 document.execCommand = jest.fn()expect(document.execCommand).toHabeBeenCalledWith('copy')
猜你喜欢
  • 2012-01-08
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 2013-09-30
  • 2013-01-21
  • 2019-01-05
  • 2011-03-16
相关资源
最近更新 更多