如何在摩卡单元测试中模拟对象?

How to mock object in mocha unittest?

在我的 reactjs 组件中,我有一个名为 getContainer(doc) 的方法,其中包含以下行:

  let w = Math.max(doc.documentElement.clientWidth, window.innerWidth);

它需要 1 个名为 doc 的参数:htmldocument。在我的摩卡单元测试中,我得到了:

let mockDoc =  {documentElement: {clientWidth:100}}
let res = wrapper.instance().getContainer(mockDoc);

当我 运行 测试时仍然出现错误,我该如何解决?

错误:

 TypeError: Cannot read property 'clientWidth' of undefined

你可以使用像jsdom这样的可视化dom库,更多细节你可以看jsdom.it is simple to use.here is a demo by enzyme