gpt4 book ai didi

polymer - 如何在 Web Component Tester 中模拟全局变量

转载 作者:行者123 更新时间:2023-12-02 04:37:14 26 4
gpt4 key购买 nike

在某些情况下,我们的 Polymer 元素具有依赖于全局行为的方法,例如视口(viewport)大小检测或注入(inject)全局变量的分析包。

现在我正在尝试使用 Web Component Tester 测试这些方法,但我看不到如何注入(inject),例如 stub 到 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();
});

最佳答案

您可以尝试使用 before 或 beforeEach 以及 after 或 afterEach 钩子(Hook)。

  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 stub 属性。

var sandbox = sinon.sandbox.create();
sandbox.stub(window, "Analytics", undefined);

// then restore when finished like above
sandbox.restore();

关于polymer - 如何在 Web Component Tester 中模拟全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41140903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com