Javascript 如何使用 mocha/chai 模拟窗口/文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36500723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock window/document with mocha/chai
提问by Jeanluca Scaljeri
When I try to unit test the getElement
function
当我尝试对getElement
函数进行单元测试时
class BarFoo {
getElement() {
return document.querySelector('#barfoo');
}
}
mocha doesn't know anything about document
, so I figured that you might do something like this:
mocha 对 一无所知document
,所以我想你可能会做这样的事情:
beforeEach(() => {
global.document = {
querySelector: () => { ... }
}
}
Although this works, I'm wondering if this is the correct approach and maybe there is a package available to solve this issue, because my approach can get laborious if more browser API's are used ?
虽然这有效,但我想知道这是否是正确的方法,也许有一个包可以解决这个问题,因为如果使用更多的浏览器 API,我的方法会变得很费力?
回答by Jeremy J Starcher
There are a few options available to you:
有几个选项可供您使用:
Option 1: Use JSDOM
选项 1:使用JSDOM
By adding a DOM to your code, you can unit test much of your client-side code within node.js
通过向代码中添加 DOM,您可以在 node.js 中对大部分客户端代码进行单元测试
Option 2: Use MOCHA on the client
选项 2:在客户端使用 MOCHA
Mocha does run inside the client and you can use separate client-side unit tests. This tends to be my preferred approach as I can test against specific browsers and not a specific JS implantation.
Mocha 确实在客户端内部运行,您可以使用单独的客户端单元测试。这往往是我的首选方法,因为我可以针对特定浏览器而不是特定 JS 植入进行测试。
Option 3: Use PhantomJS
选项 3:使用PhantomJS
PhantomJS allows you to control a headless browser within your testing environment.
PhantomJS 允许您在测试环境中控制无头浏览器。
Option 4: Headless Chrome
选项 4:无头 Chrome
Now that Headless Chrome is out, the PhantomJS maintainer has retired.
现在 Headless Chrome 已经过时了,PhantomJS 的维护者已经退休了。
回答by Simon Bengtsson
I have been writing tests similar to what you proposed when I just needed to mock a certain function on window:
当我只需要在窗口上模拟某个函数时,我一直在编写类似于您提出的测试:
it('html test', function () {
const windowRef = global.window;
global.window = {document: {querySelector: () => null}};
const lib = require('lib-that-uses-queryselector');
assert(true);
global.window = windowRef;
});
I have been using mock-browserin other tests when I wanted a more complete window object:
当我想要一个更完整的窗口对象时,我一直在其他测试中使用模拟浏览器:
it('html test', function () {
const windowRef = global.window;
const MockBrowser = require('mock-browser').mocks.MockBrowser;
global.window = new MockBrowser().getWindow();
const lib = require('lib-that-uses-window');
assert(true);
global.window = windowRef;
});
Note that you probably want to restore the window object (global.window = windowRef;
above) after messing with globals.
请注意,您可能想global.window = windowRef;
在弄乱 globals之后恢复 window 对象(上面)。