如何用mocha / chai模拟窗口/文档
当我尝试unit testinggetElement
函数
class BarFoo { getElement() { return document.querySelector('#barfoo'); } }
摩卡对document
一无所知,所以我想你可能会这样做:
beforeEach(() => { global.document = { querySelector: () => { ... } } }
虽然这有效,但我想知道这是否是正确的方法,也许有解决这个问题的软件包,因为如果使用更多的浏览器API,我的方法可能会很费力。
我一直在写testing类似于你刚才需要在窗口上模拟某个函数时所提出的testing:
it('html test', function () { const window = global.window; global.window = {document: {querySelector: function () { return null; }}}; let lib = require('lib-that-uses-queryselector'); assert(true); global.window = window; });
当我想要一个更完整的窗口对象时,我在其他testing中一直使用模拟浏览器 :
it('html test', function () { const window = global.window; let MockBrowser = require('mock-browser').mocks.MockBrowser; global.window = new MockBrowser().getWindow(); let lib = require('lib-that-uses-window'); assert(true); global.window = window; });
请注意,您可能想要在全局variables之后恢复窗口对象( global.window = window;
above)。
有几个选项可供您使用:
选项1:使用JSDOM
通过添加一个DOM到你的代码中,你可以在node.js中unit testing你的客户端代码
选项2:在客户端使用MOCHA
摩卡确实运行在客户端,你可以使用单独的客户端unit testing。 这往往是我的首选方法,因为我可以testing针对特定的浏览器,而不是一个特定的JS植入。
选项3:使用PhantomJS
PhantomJS允许您在testing环境中控制无头浏览器。