测试对象中事件处理的最佳方法是什么?我似乎无法弄清楚这一点。
我有一个对象,它设置了一些事件侦听器,当它观察到这些事件被触发时,它会更改页面上的一个 dom 对象。当我进行多个测试时,下面示例中的最后一个测试失败,如果我注释掉其他的就可以了。
我有一个看起来像的测试套件
var TitleTest = TestCase('TitleTest');
TitleTest.prototype.defaultTitle = 'title';
TitleTest.prototype.defaultCount = '0';
TitleTest.prototype.setUp = function() {
var titleObj;
this.div = new Element('div');
$$('body').first().insert(this.div);
this.div.insert('<div id="title"><h1><span id="titleCaption">' + this.defaultTitle + '</span><span id="titleCount">' + this.defaultCount + '</span></h1></div>');
titleObj = new Title();
});
TitleTest.prototype.testNewItemsEvent = function() {
var data = {count: 10};
assertEquals('Count should be zero before events are fired', this.defaultCount, $('titleCount').innerHTML);
document.fire('custom:NewItems', data);
assertEquals('New count should be 10', data.count + '', $('titleCount').innerHTML);
});
// ... a few other simple tests like the one above
TitleTest.prototype.testUpdateSpecial = function() {
var data = {caption: 'Special Title', count: 10},
specialObj = {special: {type: 2, value: 5}};
// Emulate a special type of category, that can only be
// added at page load
document.fire('custom:UpdateTitle', data);
assertEquals(data.caption, $('titleCaption').innerHTML);
assertEquals(data.count, $('titleCount').innerHTML);
//Removing the special category should revert the title to its default
document.fire('custom:RemoveSpecial', specialObj);
assertEquals(this.defaultTitle, $('titleCaption').innerHTML);
assertEquals(this.defaultCount, $('titleCount').innerHTML);
// only way to get this added back in during non load is using
// javascript history so it needs to revert to previous state
document.fire('custom:AddSpecial', specialObj);
assertEquals(data.caption, $('titleCaption').innerHTML);
assertEquals(data.count + '', $('titleCount').innerHTML);
});
如果前面的测试运行,最后一对断言将始终失败,但如果我注释掉其他测试,则将通过。我不知道我能做些什么来让它工作。
编辑:这是处理特殊标题的添加/删除的代码
Event.observe(document, 'custom:UpdateTitle', function(event) {
if (event.memo.caption) {
this._updateCaption(event.memo.caption);
}
if (event.memo.count) {
this._updateCount(event.memo.count);
}
}.bind(this));
Event.observe(document, 'custom:RemoveSpecial', function(event) {
if (
event.memo.special.type === 1 ||
event.memo.special.type === 2 ||
(
event.memo.special.type === 3 &&
parseInt(event.memo.special.value, 10) === 8
)
){
this._previousTitle = $('titleCaption').innerHTML;
this._resetTitle();
}
}.bind(this));
Event.observe(document, 'custom:AddSpecial', function(event) {
if (
event.memo.special.type === 1 ||
event.memo.special.type === 2 ||
(
event.memo.special.type === 3 &&
parseInt(event.memo.special.value, 10) === 8
)
){
if (!this._previousTitle.blank()) {
this._updateCaption(this._previousTitle);
}
}
}.bind(this));