2016-12-14 80 views
2

我们有几种情况,其中我们的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(); 
    }); 
+1

你可以添加一个例子吗? – Gordon

+0

@戈登编辑,见上文。 – Vincent

回答

0

你可以尝试使用之前或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(); 
+0

但是,这仍然是'window'对象_inside我的tests_,而我想访问可用于我的应用程序。所以像webdriver的[执行](http://webdriver.io/api/protocol/execute.html),但Web组件测试器。 – Vincent

+0

您的示例中需要更多信息。一般来说,测试只是针对你想测试的功能。如果还有其他功能超出了功能范围,则可以对其行为进行存根。 – Gordon

+0

嗨,戈登,检查你的组件是否有这样的东西:let Analytics = window.Analytics;如果你有这意味着你保持一个参考和清洁窗口的参考将为时已晚。 –