【发布时间】:2017-08-08 09:09:08
【问题描述】:
在我的单元测试中,我希望能够用模拟元素替换元素,并为原始元素的方法提供存根。
例如,假设我的组件的模板是这样的:
<template>
<my-other-element id="myOtherElement"></my-other-element>
</template>
让我们稍后在我的元素中说我做了这样的事情:
myMethod: function () {
this.$.myOtherElement.foo();
}
当我为我的元素编写单元测试时,我想做以下事情:
- 模拟整个
<my-other-element> - 为
foo()提供存根方法
我找到了一种方法来实现这一点,但不知何故它似乎不是很干净。我目前的解决方案如下:
var fooStub;
beforeEach(function () {
fooStub = sinon.stub();
replace('my-other-element').with('fake-my-other-element');
document.createElement('fake-my-other-element').constructor.prototype = {
foo: fooStub
};
element = fixture('basic');
});
我想知道是否有更好的方法来实现相同的结果。不知何故,创建一个空元素以更改 prototype 属性以添加存根似乎不是最好的方法。
我知道你也可以这样做:
stub('my-other-element', {
foo: fooStub
});
但我更喜欢总是提前模拟所有内容,以确保子元素没有副作用。
【问题讨论】:
标签: javascript unit-testing testing polymer polymer-2.x