在我的单元测试中,我希望能够用模拟元素替换元素,并为原始元素的方法提供 stub 。
例如,假设我的组件模板是这样的:
<template>
<my-other-element id="myOtherElement"></my-other-element>
</template>
让我们稍后在我的元素中做这样的事情:
myMethod: function () {
this.$.myOtherElement.foo();
}
当我为我的元素编写单元测试时,我想执行以下操作:
- 模拟整个
<my-other-element>
- 为
foo()
提供 stub 方法
我找到了一种方法来实现这一点,但不知何故它似乎不是很干净。我目前的解决方案如下:
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 的属性似乎不是最好的方法。
我知道你也可以这样做:
stub('my-other-element', {
foo: fooStub
});
但我更喜欢总是提前模拟所有内容,以确保没有来自子元素的副作用。
最佳答案
我使用了一些选项。一种是主动将这些方法添加到有问题的元素中
chai.should();
suite('let\s stub a child method', () => {
let testView;
setup(() => {
replace('child-el').with('fake-child-el');
testView = fixture('basic');
testView.$.child.method = sinon.stub();
});
test('myMethod() calls child method', () => {
testView.myMethod();
testView.$.child.method.should.have.been.called;
});
});
另一个是创建一个假元素来 stub 并包装它的方法
Polymer({is: 'fake-child-el', method: sinon.stub;});
chai.should();
suite('let\s stub a child method', () => {
let testView;
setup(() => {
replace('child-el').with('fake-child-el');
testView = fixture('basic');
});
test('myMethod() calls child method', () => {
testView.myMethod();
testView.$.child.method.should.have.been.called;
});
});
这可能不适用于所有浏览器。
编辑:在第二种方法失败的情况下,我已经使 stub 元素的方法类似于 method: () => null
,然后将该方法包装在 sinon.stub( ) 在测试套件中调用。
关于javascript - 如何替换 Polymer 中的元素和 stub 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564106/