Web組件測試器(WCT)用於測試聚合物元素。要測試模板中繼器的過濾功能,有兩個相關點從Polymer Testing Guide:
https://www.polymer-project.org/1.0/tools/tests.html#test-fixtures
使用測試夾具:
- 定義測試夾具模板,並給它一個ID 。
- 在測試腳本中定義一個變量來引用模板。
- 在您的setup()方法中實例化一個新的fixture實例。
https://www.polymer-project.org/1.0/tools/tests.html#test-dom-mutations
始終包裹在測試中flush
如果你的組件模板中包含模板中繼器(dom-repeat
)或有條件的模板(dom-if
),或者如果你的測試涉及地方DOM突變。在某些情況下,聚合物懶惰地執行這些操作以獲得性能。 flush
確保已發生異步更改。測試函數應該採用一個參數done
來指示它是異步的,並且它應該在flush
的末尾調用done()
。
考慮:
<dom-module id="x-foo">
<template>
<input type="text" placeholder="filter" value="{{filterVal::input}}">
<ul>
<template is="dom-repeat" items="{{fields}}" filter="{{_queryFilter(filterVal)}}">
<li class="name">{{item.name}}</li>
</template>
</ul>
</template>
<script>...</script>
</dom-module>
你test.html
會是這個樣子:
<test-fixture id="basic">
<template>
<x-foo></x-foo>
</template>
</test-fixture>
<script>
suite('<x-foo>', function() {
var list, listItems;
setup(function() {
list = fixture('basic');
});
test('filters fields', function(done) {
list.fields = [
{name: 'foo'},
{name: 'bar'}
];
list.filterVal = 'f';
flush(function() {
listItems = Polymer.dom(list.root).querySelectorAll('li.name');
assert.equal(1, listItems.length);
assert.equal('foo', listItems[0].textContent);
done();
});
});
});
</script>
爲_queryFilter()
單元測試看起來是這樣的:
test('_queryFilter() performs filtering', function() {
var filter = list._queryFilter('o');
var passedFilter = function(field) {
return filter(field) !== 0;
};
assert.isTrue(passedFilter({name: 'foo'}));
assert.isFalse(passedFilter({name: 'bar'}));
});
我建議玩Polymer Starter Kit,它已經包含了一些搭配WCT腳架的測試元件(例如app/test/my-list-basic.html
)。