【问题标题】:How to mock global variables in Web Component Tester如何在 Web Component Tester 中模拟全局变量
【发布时间】:2016-12-14 10:58:28
【问题描述】:

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

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

【问题讨论】:

  • 你能举个例子吗?
  • @Gordon 已编辑,见上文。

标签: polymer mocha.js polymer-1.0 web-component-tester


【解决方案1】:

您可以尝试使用 before 或 beforeEach 和 after 或 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();

【讨论】:

  • 但这仍然在window 对象上在我的测试中,而我想访问我的应用程序可用的对象。所以类似于 webdriver 的 execute,但用于 Web Component Tester。
  • 在您的示例中需要更多信息。通常,测试仅针对您要测试的功能。如果有超出函数范围的其他函数,您可以对它们的行为进行存根。
  • 嗨,戈登,检查你的组件中是否有类似的东西: let Analytics = window.Analytics ;如果你有它意味着你正在保留一个引用并且清理窗口引用将为时已晚。
猜你喜欢
  • 2020-10-09
  • 2016-04-26
  • 1970-01-01
  • 2016-11-15
  • 2017-03-19
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
相关资源
最近更新 更多