如何在Web组件测试器中模拟全局变量
问题描述:
我们有几种情况,其中我们的Polymer元素具有依赖全局行为(例如视口大小检测)或注入全局变量的分析包的方法。如何在Web组件测试器中模拟全局变量
现在我试图使用Web组件测试器来测试这些方法,但我看不到如何注入例如存根到window
对象中(例如使用webdriver的execute函数可能)。我该怎么做呢?
没有工作,测试的例子:
test('my-element should not crash when `Analytics` is blocked', function() {
// I'd like window.Analytics in my app to be undefined,
// but this doesn't work, obviously:
window.Analytics = undefined;
myEl = fixture('my-element');
expect(myEl.ready).to.not.throw();
});
答
你可以尝试使用之前或beforeEach后或afterEach挂钩。
var tempAnalytics = window.Analytics;
before(function() {
// runs before all tests in this block
window.Analytics = undefined;
});
after(function() {
// runs after all tests in this block
window.Analytics = tempAnalytics;
});
另一种选择是使用Sinon sandboxes来存储属性。
var sandbox = sinon.sandbox.create();
sandbox.stub(window, "Analytics", undefined);
// then restore when finished like above
sandbox.restore();
你可以添加一个例子吗? – Gordon
@戈登编辑,见上文。 – Vincent